摘一段笔记:
These passages come from a book named " A byte of Python"
It's a open book which is very helpful when someone is learning python programming.
Tip: if anyone wants to learn python very well, he or she might need to check out the tutorial from http://python.org and some tutorials from youtube.
These are in the chapter of Object Oriented Programming of the book
Now I paste those hints, hope they would be helpful :D
class Robot:
‚‚‚Represents a robot, with a name.‚‚‚
# A class variable, counting the number of robots
population = 0
def __init__(self, name):
‚‚‚Initializes the data.‚‚‚
self.name = name
print(‚(Initializing {0})‚.format(self.name))
# When this person is created, the robot
# adds to the population
Robot.population += 1
def __del__(self):
‚‚‚I am dying.‚‚‚
print(‚{0} is being destroyed!‚.format(self.name))
Robot.population -= 1
if Robot.population == 0:
print(‚{0} was the last one.‚.format(self.name))
else:
print(‚There are still {0:d} robots working.‚.format(Robot.population))
def sayHi(self):
‚‚‚Greeting by the robot.
Yeah, they can do that.‚‚‚
print(‚Greetings, my masters call me {0}.‚.format(self.name))
def howMany():
‚‚‚Prints the current population.‚‚‚
print(‚We have {0:d} robots.‚.format(Robot.population))
howMany = staticmethod(howMany)
droid1 = Robot(‚R2-D2‚)
droid1.sayHi()
Robot.howMany()
droid2 = Robot(‚C-3PO‚)
droid2.sayHi()
Robot.howMany()
print("\nRobots can do some work here.\n")
print("Robots have finished their work. So let‚s destroy them.")
del droid1
del droid2
Robot.howMany()
Output:
$ python3 objvar.py
(Initializing R2-D2)
Greetings, my masters call me R2-D2.
We have 1 robots.
(Initializing C-3PO)
Greetings, my masters call me C-3PO.
We have 2 robots.
Robots can do some work here.
Robots have finished their work. So let’s destroy them.
R2-D2 is being destroyed!
There are still 1 robots working.
C-3PO is being destroyed!
C-3PO was the last one.
We have 0 robots.
How it works:
The __del__ method is run when the object is no longer in use and there is
no guarantee when that method will be run. If you want to explicitly see it in
action, we have to use the del statement which is what we have done here.
All class members are public.
One exception: If you use data members with
names using the double underscore prefix such as __privatevar,Python uses
name-mangling to effectively make it a private variable.
Thus, the convention followed is that any variable that is to be used only within
the class or object should begin with an underscore and all other names are
public and can be used by other classes/objects. Remember that this is only
a convention and is not enforced by Python (except for the double underscore
prefix).
"""The howMany is actually a method that belongs to the class and not to the
object. This means we can define it as either a @classmethod or a @staticmethod
depending on whether we need to know which class we are part of. Since we
don’t need such information, we will go for staticmethod .
We could have also achieved the same using decorators(@):"""
@staticmethod
def howMany():
Prints the current population.
print('We have {0:d} robots.'.format(Robot.population))
下面是一些自己的编辑的,看到youtube上有人这么做, i followed him. and it works.
这一段是python2.7.3的
class Superhero:
"""
To make the variables of an object, we put __ in front of variables
"""
__superhero_count = 0
def __init__(self,name = "", hungry = False, tired = False):
self.__name = name
self.__hungry = hungry
self.__tired = tired
Superhero.__superhero_count += 1
@staticmethod # To declare an empty item :D
def get_superhero_count():
return Superhero.__superhero_count
#instance methods
def mowGrass(self):
print self.__name + " is mowing the grass."
self.__tired = True
self.__hungry = True
def nap(self):
print self.__name + " is taking a nap."
self.__tired = False
def eat(self, food):
print self.__name + " is eating " + food + "."
self.__hungry = False
def throwParty(self, superhero, food):
print self.__name + " is throwing a party for " + superhero.__name + "."
self.eat(food)
superhero.eat(food)
def fly(self):
print self.__name + " is flying."
self.__tired = True
def __str__(self):
if self.__tired:
tired_s = "tired"
else:
tired_s = "not tired"
if self.__hungry:
hungry_s = "hungry"
else:
hungry_s = "not hungry"
return "%s is %s and %s" % (self.__name, tired_s, hungry_s )
def main():
hulk = Superhero("The Hulk", True, False)
print hulk
hulk.mowGrass()
print hulk
hulk.eat("banana")
print hulk
hulk.nap()
print hulk
hulk.fly()
print hulk
superman = Superhero("The Superman", False, False )
hulk.throwParty(superman,"lemon")
print hulk
print superman
if __name__=="__main__":
main()
输出结果为
The Hulk is not tired and hungry
The Hulk is mowing the grass.
The Hulk is tired and hungry
The Hulk is eating banana.
The Hulk is tired and not hungry
The Hulk is taking a nap.
The Hulk is not tired and not hungry
The Hulk is flying.
The Hulk is tired and not hungry
The Hulk is throwing a party for The Superman.
The Hulk is eating lemon.
The Superman is eating lemon.
The Hulk is tired and not hungry
The Superman is not tired and not hungry
下面一段是python3.3.0的。这两段只要把print的改一下就好了。当然,py2 3区别不光在这里
I added some lines for "superman". take a look !
These codes is from one of my Archlinux virtual machine. I copied it here using Vim. :D (ggVGy)
class Superhero:
__superhero_count = 0
def __init__(self,name = "", hungry = False, tired = False):
self.__name = name
self.__hungry = hungry
self.__tired = tired
Superhero.__superhero_count += 1
@staticmethod
def get_superhero_count():
return Superhero.__superhero_count
#instance methods
def mowGrass(self):
print(self.__name + " is mowing the grass.")
self.__tired = True
self.__hungry = True
def nap(self):
print(self.__name + " is taking a nap.")
self.__tired = False
def eat(self, food):
print(self.__name + " is eating " + food + ".")
self.__hungry = False
def throwParty(self, superhero, food):
print(self.__name + " is throwing a party for " + superhero.__name + ".")
self.eat(food)
superhero.eat(food)
def fly(self):
print(self.__name + " is flying.")
self.__tired = True
def __str__(self):
if self.__tired:
tired_s = "tired"
else:
tired_s = "not tired"
if self.__hungry:
hungry_s = "hungry"
else:
hungry_s = "not hungry"
return "%s is %s and %s" % (self.__name, tired_s, hungry_s )
def main():
hulk = Superhero("The Hulk", True, False)
print(hulk)
hulk.mowGrass()
print(hulk)
hulk.eat("banana")
print(hulk)
hulk.nap()
print(hulk)
hulk.fly()
print(hulk)
superman = Superhero("The Superman", False, False )
superman.mowGrass()
print(superman)
hulk.throwParty(superman,"Apple")
print(hulk)
print(superman)
if __name__=="__main__":
main()
输出的结果是:
:!python /home/newbie/Desktop/class_superhero.py
The Hulk is not tired and hungry
The Hulk is mowing the grass.
The Hulk is tired and hungry
The Hulk is eating banana.
The Hulk is tired and not hungry
The Hulk is taking a nap.
The Hulk is not tired and not hungry
The Hulk is flying.
The Hulk is tired and not hungry
The Superman is mowing the grass.
The Superman is tired and hungry
The Hulk is throwing a party for The Superman.
The Hulk is eating Apple.
The Superman is eating Apple.
The Hulk is tired and not hungry
The Superman is tired and not hungry
=============
In the next blog I will show us some thing about
def __str__(self):
pass
def __die__(self):
pass
def __add__(self):
pass