HOME - Recent Changes - Search:

Academic Work


Personal

* pot de départ


dblp


(:twitter:)

-----

[ edit | logout ]
[ help | sandbox | passwd ]

Classes

#############################

class Person:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return "Person(name: " + self.name + ")"

####################

class Man(Person):
    def __init__(self, name, age):   # Note 3, don't forget to call the ancestor's __init__
        Person.__init__(self, name)   # Note 1, include self
        self.age = age

    def __str__(self):
        return "Man(name: " + self.name + ", age: " + str(self.age) + ")"

####################

joe = Person('joe')   # Note 2, don't include self
print joe   # Person(name: joe)

lac = Man('lac', 32)
print lac   # Man(name: lac, age: 32)

All data attributes of a class are initialized in the __init__ method. Tip: always assign an initial value to all data attributes in the __init__ method! It'll save you hours of debugging.

Note 1 & 2: When you call a method of the ancestor class from your class, you MUST include the self argument! However, when you call a class method from outside, you don't need to specify the self argument.

Note 3: __init__ methods are optional, but if you define one, then you must call the ancestor's __init__ method! This is not called automatically for you.

Class Attributes

class Count:
    cnt = 0   # class attributes are here; data attribute go to __init__

    def __init__(self):
        self.__class__.cnt += 1
        # or: Count.cnt += 1

####################

print Count.cnt   # 0, works without instances

cnt = Count()
print cnt.cnt     # 1

cnt2 = Count()
print cnt2.cnt    # 2

print Count.cnt   # 2

Here cnt is a class attribute, i.e. it is common for all the instances of the class Count. There are two ways to modify its value from __init__:

  • self.__class__.cnt += 1, or
  • Count.cnt += 1
Cloud City


anime | bash | blogs | bsd | c/c++ | c64 | calc | comics | convert | cube | del.icio.us | digg | east | eBooks | egeszseg | elite | firefox | flash | fun | games | gimp | google | groovy | hardware | hit&run | howto | java | javascript | knife | lang | latex | liferay | linux | lovecraft | magyar | maths | movies | music | p2p | perl | pdf | photoshop | php | pmwiki | prog | python | radio | recept | rts | scala | scene | sci-fi | scripting | security | shell | space | súlyos | telephone | torrente | translate | ubuntu | vim | wallpapers | webutils | wikis | windows


Blogs and Dev.

* Ubuntu Incident
* Python Adventures
* me @ GitHub


Places

Debrecen | France | Hungary | Montreal | Nancy


Notes

full circle | km


Hobby Projects

* Jabba's Codes
* PmWiki
* Firefox
* PHP
* JavaScript
* Scriptorium
* Tutorials
* me @ GitHub


Quick Links


[ edit ]

View - Edit - History - Attach - Print *** Report - Recent Changes - Search
Page last modified on 2009 November 12, 03:33