[Tutor] Declaration order of classes... why it is important?

Dave Angel davea at ieee.org
Wed Aug 26 21:19:37 EDT 2009


(Looks like you posted privately to me;  should use Reply-all.  I'm 
copying entire message here so others can add to my comments)

Mac Ryan wrote:
> On Wed, 2009-08-26 at 15:46 -0400, Dave Angel wrote:
>   
>> So define a classmethod to finish the job, and invoke it later
>>
>> class Employee(object):
>>     @classmethod
>>     def finish(cls):
>>         cls.__storm_table__ = "employee"
>>         cls.company_id = []
>>         cls.company = Company.id         #where Company is a forward 
>> reference
>>         del cls.finish      #remove this method so it won't be called a 
>> second time
>>
>> class Company:
>>     id = 42
>>
>> Employee.finish()   #This finishes initializing the class
>>
>>
>> help(Employee)
>> print Employee.company_id
>>     
>
> First things first, thank you Wayne, Kent and Dave for your extensive
> and complementary explanations. As many things in python, what it seemed
> obscure at first now - with your help - seems perfectly obvious.
>
> Second thing: the example that Dave gave me and that I left quoted above
> makes use of decorators, but this is something that I still do not
> understand. I believe I got a grasp of the concept of metaclasses, to
> which the concept of decorator seems to be related, but the official
> documentation is a a bit obscure for me.
>
> I don't want to steal your time asking for an explanation that probably
> is already somewhere out there, but my google searches did not return
> anything useful (I assume I am using the wrong keywords here), so if you
> have a good pointer for me, I would be very grateful. :)
>
> Mac.
>
>
>   
Decorators are syntactic sugar to save typing;  what they accomplish can 
always be done another way, but generally not as readable.

#somebody (eg., Python library) defines a function that takes a function 
as parameter, and returns a function, generally a different one related 
to the first
def  mydecorator(funct):
      ....
      return newfunct


class  myclass(object):
     @mydecorator
      def  mymethod(self, arg1, arg2):
              ...

Instead of the @syntax, we could also have written:

class  myclass(object):
      def mymethod(self, arg1, arg2)
            ....
      mymethod = mydecorator(mymethod)             #this call happens 
when the class is being created


Now there are a couple of decorators that are in the standard library 
that everyone should know about:    classmethod() and staticmethod().  
They wrap a method in a new one (which ends up having the same name), 
such that the first argument is either eaten (staticmethod), or changed 
to a class (classmethod).

Hope that was sufficient detail.

DaveA




More information about the Python-list mailing list