Referring to class methods in class attributes
Jean-Michel Pichavant
jeanmichel at sequans.com
Wed Feb 17 13:53:59 EST 2010
mk wrote:
> Stephen Hansen wrote:
>
>> You don't have to (and can't) refer to the class within the body.
>> Class statements are sort of... odd. They are code which is directly
>> executed, and the results are then passed into a
>> metaclass/type/whatever and a class object is created. While within
>> the class body, the class doesn't exist yet.
>>
>> But you don't need it to.
>>
>> Just do:
>>
>> 'internal_date': print_internal_date
>>
>> The 'def' is in the same local scope as 'tagdata' is.
>
> Thanks, that worked. But in order to make it work I had to get rid of
> 'self' in print_internal_date signature, bc all other functions in
> tagdata have only a single argument:
>
> class PYFileInfo(FileInfo):
> 'python file properties'
>
> def print_internal_date(filename):
> ...
>
> tagdata = {'compiled_fname': lambda x: x + 'c',
> 'size': os.path.getsize,
> 'internal_date': print_internal_date
> }
>
> That looks weird: a method with no 'self'. Hmm that is probably
> seriously wrong.
> [snip]
Absolutely not. It's called a static method, you have to decorate it
with @staticmethod though.
class A:
@staticmethod
def getInstance():
return A()
a = A.getInstance()
you have also the class method version:
class B:
@classmethod:
def getInstance(cls): # class methods take a class as first parameter
return cls()
JM
More information about the Python-list
mailing list