How to use a parameter in a class
svetoslav.agafonkin at gmail.com
svetoslav.agafonkin at gmail.com
Sat May 3 07:52:01 EDT 2008
On May 3, 1:05 pm, Decebal <CLDWester... at gmail.com> wrote:
> I have the following class:
> #####
> class Dummy():
> value = 0
> def __init__(self, thisValue):
> print thisValue
> self.value = thisValue
> value = thisValue
>
> def testing(self):
> print 'In test: %d' % self.value
>
> def returnValue(self):
> return self.value
>
> result = someFuntion(default = value)
> #####
>
> But the last line does not work.
> I would like to do a call like:
> dummy = Dummy(thisValue = 12)
>
> And that someFunction gets a default value of 12. How can I do that?
The line
> result = someFuntion(default = value)
is executed when the whole 'class' compound statement is executed,
i.e.
before the line that creates the 'dummy' instance. Moreover, this
happens only once and not every time you create a new instance of
the class. If you want 'result' to be a class attribute that is set
every time you create a new instance move the line
> result = someFuntion(default = value)
in the __init__ constructor (you also have to assign some value to it
before,
just like the 'value' attribute and preffix it with Dummy. otherwise
it'll
be considered as local name of __init__):
class Dummy():
value = 0
result = 0
def __init__(self, thisValue):
print thisValue
self.value = thisValue
Dummy.value = thisValue
Dummy.result = someFuntion(default = Dummy.value)
def testing(self):
...
More information about the Python-list
mailing list