Python和其他面向对象语言一样没有多少区别。过程就是这样:定义类,定义函数,创建对象,调用方法完成功能。继承就是类名后面加上() 然后加入父类的名称就OK
相对而言,要注意的就是self其实相当于java中的this,定义函数时,无参数的时候要加上这个self。具体看这个demo:class Person:
class Person:
count = 0
def __init__(self,name):
self.name =name
Person.count+=1
def say(self):
print("this is ", self.name)
Person.count-=1
def showCount(self):
if(Person.count ==1):
print("this is just a start")
if(Person.count ==0):
print("this is just an end")
class Man(Person):
def __init__(self,name,age):
Person.__init__(self,name)
self.age = age
def say(self):
Person.say(self)
print("this is from person", self.name)
def showCount(self):
if(Person.count ==2):
print("this is just a start from Man")
if(Person.count ==0):
print("this is just an end from Man")
p = Person("shuofeng")
p.showCount()
p.say()
p.showCount()
man = Man("lxy",26)
man.showCount()
man.say()
man.showCount()
执行结果当然比较简单 就是打印
this is just a start
this is shuofeng
this is just an end
this is lxy
this is from person lxy
this is just an end from Man
说明:这里的count就像是static 声明的一个静态变量一样。
PS:if else while等控制流和java区别不大,continue,break照常使用。
分享到:
2011-02-25 21:36
浏览 860
评论