Classes Python
Classes Python
Python
Information hiding
Abstraction
Encapsulation
Modularity
Polymorphism
Inheritance
simple_critter.py
dog = Puppy()
dog['Max'] = 'brown'
dog['Ruby'] = 'yellow’
print "Max is", dog['Max']
17
Using Class Attributes and Static
Methods
Class attribute: A single attribute that’s
associated with a class itself (not an instance!)
Static method: A method that’s associated with a
class itself
Class attribute could be used for counting the total
number of objects instantiated, for example
Static methods often work with class attributes
def status():
print "Total critters", Critter.total
status = staticmethod(status)
20
Creating a Static Method
class Critter(object):
...
def status():
print "Total critters", Critter.total
status = staticmethod(status)
status()
– Is static method
– Doesn't have self in parameter list because method
will be invoked through class not object
staticmethod()
– Built-in Python function
– Takes method and returns static method
21
Invoking a Static Method
...
crit1 = Critter("critter 1")
crit2 = Critter("critter 2")
crit3 = Critter("critter 3")
Critter.status()
Critter.status()
– Invokes static method status() defined in Critter
– Prints a message stating that 3 critters exist
– Works because constructor increments class
attribute total, which status() displays
classy_critter.py
Guide to Programming with Python 22
Setting default values
class Person(object):
def __init__(self, name="Tom", age=20):
self.name = name
self.age = age
def talk(self):
print "Hi, I am", self.name
def __str__(self):
return "Hi, I am " + self.name
two = Person()
print two