小结主要讲述面向对象的优点,可扩展性高
示例代码如下:
1 class Chinese: 2 def __init__(self,name,age,sex): 3 self.name=name 4 self.age=age 5 self.sex=sex 6 7 8 p1 = Chinese(‘egon‘,18,‘male‘) 9 p2 = Chinese(‘alex‘,38,‘female‘) 10 p3 = Chinese(‘wpq‘,48,‘female‘)
我们往类中插入一个数据属性,只需在类中添加即可,对象不需做什么改动就可以访问,代码验证如下:
1 class Chinese: 2 country = ‘China‘ 3 def __init__(self,name,age,sex): 4 self.name=name 5 self.age=age 6 self.sex=sex 7 8 9 p1 = Chinese(‘egon‘,18,‘male‘) 10 p2 = Chinese(‘alex‘,38,‘female‘) 11 p3 = Chinese(‘wpq‘,48,‘female‘) 12 13 print(p1.country) 14 print(p2.country) 15 print(p3.country)
结果如下:
China
China
China 证明都可以访问
插入一个函数属性,只需在类中添加即可,对象不需做什么改动就可以访问,代码验证如下:
1 class Chinese: 2 country = ‘China‘ 3 def __init__(self,name,age,sex): 4 self.name=name 5 self.age=age 6 self.sex=sex 7 8 def eat(self): 9 print(‘%s is eating‘ % self.name) 10 11 12 p1 = Chinese(‘egon‘,18,‘male‘) 13 p2 = Chinese(‘alex‘,38,‘female‘) 14 p3 = Chinese(‘wpq‘,48,‘female‘) 15 16 p1.eat() 17 p2.eat() 18 p3.eat()
结果如下:
egon is eating
alex is eating
wpq is eating