Tuesday, June 08, 2010

Python classes


class OldClass:

    def method(self):


Characterized by:

P = OlcClass()

p.__class__ à 'OldClass'

type(p) à 'instance'


>>> class Test:

    def __init__(self):

        print 'Test initialized'

    def meth(self):

        self.member = 1

        print 'Test.member = ' + str(self.member)


>>> class TestKid(Test):

    "This is derived from Kid, meth is overriden and so is member"

    def __init__(self):

        print 'Kid initialized'

    def meth(self):

        self.member = 2


print 'Kid.member = ' + str(self.member)


Above is shown how to override a method, call its parent implementation; the member attribute is shared between the parent and child classes and hence calling a function in parent which references it will modify it in the child as well. The parent constructor (or any other overridden function) is not called by default.


>>> class Test(object):

Type(p) would return 'Test'. Unifies types and classes.

It has classmethods and staticmethods.

Also (for both old and new):

P = Test() ; calling a class object yields a class instance

p.__dict__ à {'member':1}

p.__dict__['member'] = 1 ; same as p.member


You can use properties (almost .NET-style) to access class attributes with new classes.