problem with Python class creating
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Thu Oct 18 15:48:30 EDT 2007
dmitrey a écrit :
> Hi all,
> I have the code like this one:
>
> from myMisc import ooIter
> class MyClass:
Unless you have a need for compatibility with aged Python versions,
you'd be better using new-style classes:
class MyClass(object):
> def __init__(self): pass
This is the default behaviour, so you may as well get rid of this line.
> iterfcn = lambda *args: ooIter(self) # i.e pass the class instance
> to other func named ooIter
cf below about this...
> field2 = val2
> field3 = val3 # etc
You're aware that these two attributes are *class* attributes (that is,
shared by all instances) ?
> So it yields "global name 'self' is not defined", that is true.
Indeed.
> How
> could I handle the situation?
iterfcn = lambda self: ooIter(self)
which could as well be written:
def iterfcn(self):
ooIter(self)
Remember that Python's methods are - at least at this stage - plain
functions, so the 'self' parameter is *not* optional - else how could
the function access the current instance ?
And FWIW, you don't need the *args if you don't use any other than 'self'.
> Currently I do (and it works, but give me some troubles - I should
> call MyClass.__init__ for each children class,
Not unless these classes define their own initializers. But that's
another problem
> and there are lots of
> those ones)
>
> class MyClass:
> def __init__(self):
> iterfcn = lambda *args: ooIter(self)
The real problem is that you create one anonymous function *per instance*.
> I suspect it has better solution, is it?
Indeed.
More information about the Python-list
mailing list