python之路_面向对象命名空间及组合
一、面向对象命名空间
例1:对象对对象属性的创建
class A: country = '印度' def show_name(self): print(self.name) a = A() #实例化对象 a.name = 'alex' #给对象创建一个name属性 a.show_name() #调用了showname方法,输出结果为:alex
class A: country = '印度' def show_name(self): print(self.name) a = A() a.name = 'alex' a.show_name() #输出结果:alex a.show_name = 'egon' #相当于创建了一个show_name属性 a.show_name() #报错:TypeError: 'str' object is not callable
例2:类的静态属性的调用
class A: country = '印度' def show_name(self): print(self.name) a = A() #a对象 b = A() #b对象 print(A.country) #输出结果为:印度 print(a.country) #先找a对象的内存 再找A的内存,结果为:印度 print(b.country) #结果为:印度 a.country = '中国' #给a对象创建了一个属性 print(A.country) #印度 print(a.country) #中国 print(b.country) #印度
二、面向对象组合
在一个类中以另一个类的对象做为数据属性,称为类的组合
例1:计算圆环的面积和周长
from math import pi class Circle: def __init__(self,r): self.r=r def area(self): return pi*self.r**2 def round(self): return 2*pi*self.r class Ring: def __init__(self,R,r): self.c_out=Circle(R) self.c_in=Circle(r) def area(self): return self.c_out.area()-self.c_in.area() def round(self): return self.c_out.round()+self.c_in.round() ring=Ring(10,5) print(ring.area()) print(ring.round())
例2:人具有生日、课程属性
class Birthday: def __init__(self,year,month,day): self.year=year self.month=month self.day=day class Course: def __init__(self,name,price,teacher): self.name=name self.price=price self.teacher=teacher class Person: def __init__(self,name,birth,course): self.name=name self.birth=birth self.course=course B=Birthday(1999,12,24) C=Course('python',20000,'jing') haijiao=Person('haijiao',B,C) print(haijiao.name) #haijiao print(haijiao.birth.year) #1999 print(haijiao.birth.month) #12 print(haijiao.birth.day) #24 print(haijiao.course.name) #python print(haijiao.course.price) #20000 print(haijiao.course.teacher) #jing
例3:人狗大战续
class Person: def __init__(self,name,sex,aggr,blood): self.name = name self.sex = sex self.aggr = aggr self.blood = blood self.money = 0 def attack(self,dog): dog.blood -= self.aggr def equip(self,weapon): self.money -= weapon.price self.weapon = weapon def use_weapon(self,dog): self.weapon.hurt(dog) self.blood += self.weapon.back_blood class Dog: def __init__(self,name,kind,aggr,blood): self.name = name self.kind = kind self.aggr = aggr self.blood = blood def bite(self,person): person.blood -= self.aggr class Weapon: def __init__(self,name,attack,price,back_blood): self.name = name self.attack = attack self.price = price self.back_blood = back_blood def hurt(self,dog): dog.blood -= self.attack egon = Person('egon','不详',250,380) alex = Person('alex','不详',20,40000) dog = Dog('egg','藏獒',500,20000) 毒包子 = Weapon('毒包子',10000,200,300) egon.money = 200 if egon.money >= 毒包子.price: egon.equip(毒包子) egon.use_weapon(dog) print(egon.blood) print(dog.blood)