member functions in a class

Terry Reedy tjreedy at udel.edu
Thu Sep 18 03:55:07 EDT 2008


Karl Kobata wrote:
> I am new to python and am wondering.  When I create a class, with ‘def’ 
> functions and if this class is instantiated say 50 times.  Does this 
> mean that all the ‘def’ functions code within the class is duplicated 
> for each instance?
> 
> Can someone give me a short and simple answer as to what happens in python?

To expand slightly on Gary's answer.  Dotted names -- ob.attr -- are 
typically (but not always) resolved as follows: does ob have attribute 
attr?  If yes, get the corresponding object.  If no, does type(ob) have 
attribute attr?  If yes, get the corresponding object.  In no, look in 
the baseclasses of type(ob) in some order (details not important here).

So, instance methods are class attributes and instance.method will 
resolve to the method attribute of type(instance) -- assuming that the 
instance does not have an attribute of the same name.  Lookup for 
special methods (with reserved __xxx__ names) may go directly to the 
class and never look at the instance attributes.




More information about the Python-list mailing list