From: j vickroy on 11 May 2010 15:59 Back9 wrote: > Hi, > > Is this grammer working in Python? > > class test: > self._value = 10 > def func(self, self._value) > > When i try it, it complains about undefined self. > > i don't know why. > > TIA .... not exactly; try: class Test: _value = 10 def func(self): print id(self._value), self._value print id(Test._value), Test._value t = Test() t.func()
From: Dave Angel on 11 May 2010 16:42 Back9 wrote: > On May 11, 3:20 pm, Chris Rebert <c...(a)rebertia.com> wrote: > >> On Tue, May 11, 2010 at 12:08 PM, Back9 <backgoo...(a)gmail.com> wrote: >> >>> On May 11, 3:06 pm, Back9 <backgoo...(a)gmail.com> wrote: >>> >> <snip> >> >>>> When i try it, it complains about undefined self. >>>> >>>> i don't know why. >>>> >>>> TIA >>>> >>> Sorry >>> here is the what i meant >>> class test: >>> self._value =0 >>> def func(self, pos =elf._value) >>> >> You're still defining the class, so how could there possibly be an >> instance of it to refer to as "self" yet (outside of a method body)? >> Also, just so you know, default argument values are only evaluated >> once, at the time the function/method is defined, so `pos > self._value` is never going to work. >> >> Do you mean for self._value to be a class variable (Java lingo: static >> variable), or an instance variable? >> >> Cheers, >> Chris >> --http://blog.rebertia.com >> > > self._value will be instance variable > > If you want an instance value to be your default, you'll need to us an indirect approach. There are no instances at the time the class is defined. So you want to create such a value in the __init__() method. Something like the following (untested): class Test(object): def __init__(self, initvalue): self.value = initvalue def func(self, pos = None): if pos=None: pos = self.value etc. x = Test(44) x.func(91) #uses 91 for pos x.func() #uses 44 for pos DaveA
From: Terry Reedy on 11 May 2010 17:19
On 5/11/2010 3:41 PM, Back9 wrote: > > self._value will be instance variable Then set it in the __init__ method. Read the tutorial and ref manual on Python class statements, which are a bit different from what you might be used to. |