I have to prgrams and thus, two question to ask. In the following program how does the line status = staticmethod(status) do anything? My python programming book somehow connects it to the line Critter.total += 1 but I don't see how? Please explain.
# Classy Critter
# Demonstrates class attributes and static methods
class Critter(object):
"""A virtual pet"""
total = 0
def status():
print "\nThe total number of critters is", Critter.total
status = staticmethod(status)
def __init__(self, name):
print "A critter has been born!"
self.name = name
Critter.total += 1
# main
print "Accessing the class attribute Critter.total:",
print Critter.total
print "\nCreating critters."
crit1 = Critter("critter 1")
crit2 = Critter("critter 2")
crit3 = Critter("critter 3")
Critter.status()
print "\nAccessing the class attribute through an object:",
print crit1.total
raw_input("\n\nPress the enter key to exit.")
The second program I want to know, does the self line self.__mood in the talk method refer to self in the talk method itself? Or the __init__ method where __mood was created. The same question goes for self.__private_method(). Does the self refer to the self in public_method where it was called, or again, the __init__ method/constructor?
# Private Critter
# Demonstrates private variables and methods
class Critter(object):
"""A virtual pet"""
def __init__(self, name, mood):
print "A new critter has been born!"
self.name = name # public attribute
self.__mood = mood # private attribute
def talk(self):
print "\nI'm", self.name
print "Right now I feel", self.__mood, "\n"
def __private_method(self):
print "This is a private method."
def public_method(self):
print "This is a public method."
self.__private_method()
# main
crit = Critter(name = "Poochie", mood = "happy")
crit.talk()
crit.public_method()
raw_input("\n\nPress the enter key to exit.")