[Tutor] garbage collection/class question

Alan Gauld alan.gauld at btinternet.com
Sat Jan 12 10:24:00 CET 2013


On 12/01/13 08:09, Jan Riechers wrote:

> So to rephrase what you and also other wrote:
> By setting "oakTree = Tree()" I create a new "Tree()" class instance.
> Now calls to "oakTree.grow()" access functions of the Tree class, by
> traversing to it's "Superclass" Tree.

No, they traverse to its Tree class. Superclasses are only involved when 
you use inheritance. Consider:

class Tree:
    def __init__(self,height=0):
      self.height = height

    def getHeight(self):
       return self.height

def EverGreen(Tree):    # subclass of Tree
    def __init__(self, height=0, color='green'):
        Tree.__init__(self,height)
        self.color = color

    def getColor(self):
        return self.color


t = Tree()
print t.getHeight()     # calls Tree.getHeight

g = EverGreen()
print g.getHeight()    # calls Tree.getHeight by searching superclass
print g.getColor()     # calls EverGreen.getColor

So the superclass is only used in the case of g.getHeight()
Python looks for getHeight in the class of EverGreen and can't find it. 
So it looks in the superclass Tree to see if it can find getHeight there.

> The "self" then, which also is used in the Superclass Function only
> tells, work with the "own" (self) values of the class instance, instead
> of the values of the class itself.
>
> I guess that's right.

Maybe, I'm not sure what you mean. self is a reference to the instance 
invoking the method.

> Actually Im puzzled with the difference between a classmethod and a
> regular function definition inside a class object.

All methods are functions defined inside classes. "regular functions" 
are by definition NOT defined in a class. regular functions require no 
lookup mechanism and do not have a "magic" first parameter like self.

> Does the classmethod just mean that I can use the class "math" and call
> "math.random()" without creating an instance of math before using
> "random()" ?

Maybe, if math were a class. But math is actually a module which is 
different to a class.

> Okay, that makes sense - that class functions/methods (confusing with
> that decorator to talk about)

The decorator is only used for classmethods not for instance methods.
Most of the time you don't need to use classmethods you only need 
instance methods.



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list