来源:python中国网 时间:2019-06-06

  类是对生活的抽象,生活中的事物彼此存在着关联,类与类之间也同样如此。今天介绍面向对象的世界中.类与类中的依赖、关联和组合关系。代码量大的时候,项目复杂的时候经常出现类与类之间纵横交错!

  依赖关系

# ‐*‐ coding: utf‐8 ‐*‐

class Dog:
    def __init__(self,name,age,breed,master):
        self.name = name
        self.age = age
        self.breed = breed
        self.master = master # master传进来的应该是个对象
        self.sayhi()  # 调用自己的方法在实例化的时候
    def sayhi(self):
        print("Hi, I'm %s, a %s dog, my master is %s" %(self.name,self.breed,self.master.name))

class Person:
    def __init__(self,name,age,sex):
        self.name = name
        self.age = age
        self.sex = sex
    def walk_dog(self,dog_obj):
        """遛狗"""
        print("主人[%s]带狗[%s]去溜溜。。。" % (self.name,dog_obj.name ))

p = Person("laowang",26,"Male")
d = Dog("dog_baby",5,"二哈",p)
p.walk_dog(d)
D:installpython3python.exe D:/pyscript/test/test.py
Hi, I'm dog_baby, a 二哈 dog, my master is laowang
主人[laowang]带狗[dog_baby]去溜溜。。。

Process finished with exit code 0


  关联关系  

# ‐*‐ coding: utf‐8 ‐*‐

class RelationShip:
    """保存2个人的感情关联关系"""

    def __init__(self):
        self.couple = []
    def make_couple(self,obj1,obj2):
        self.couple.append(obj1)
        self.couple.append(obj2)
        print("[%s] 和 [%s] 正式结为对象..." % (obj1.name,obj2.name))
    def break_up(self):
        if self.couple:
            print("[%s] 和 [%s] 要分手了...真好" % (self.couple[0].name,self.couple[1].name))
            self.couple.clear()
        else:
            print("你根本就没对象,你分手个蛋呀...")
    def get_my_partner(self,obj):
        """返回我的另一半"""
        for i in self.couple:
            if obj != i: # copule列表里有2个值,一个是我自己,一个是我对象,只要跟传进来的obj不相等,代表找到了我对象
                return i.name
        else:
            print("你没有对象,自己心里没有点数么....")


class Person:
    def __init__(self,name,age,sex,relation_obj):
        self.name = name
        self.age = age
        self.sex = sex
        self.relation = relation_obj # 把RelationShip对象传进来
        #self.partner = None # 另一半,是个对象

    def do_private_stuff(self):
        """和男/女盆友干点羞羞的事"""
        print("%s is doing %s in the 7th hotel." %(self.name,self.relation.get_my_partner(self)))

relation_obj = RelationShip()
p1 = Person("武大郎",25,"男",relation_obj)
p2 = Person("黑姑娘",23,"女",relation_obj)
relation_obj.make_couple(p1,p2) # 把2个人结合在一起
p1.do_private_stuff()
p2.do_private_stuff()
p1.relation.break_up() # 要分手了
p1.relation.get_my_partner(p1) # 再去查,就没有对象了
p2.relation.get_my_partner(p2) # 再去查,就没有对象了
D:installpython3python.exe D:/pyscript/test/test.py
[武大郎] 和 [黑姑娘] 正式结为对象...
武大郎 is doing 黑姑娘 in the 7th hotel.
黑姑娘 is doing 武大郎 in the 7th hotel.
[武大郎] 和 [黑姑娘] 要分手了...真好
你没有对象,自己心里没有点数么....
你没有对象,自己心里没有点数么....

Process finished with exit code 0


  组合关系(当类之间有显著不同,并且较小的类是较大的类所需要的组件时,用组合比较好)
 

# ‐*‐ coding: utf‐8 ‐*‐

class BirthDate:

    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

class Course:

    def __init__(self, name, price, period):
        self.name = name
        self.price = price
        self.period = period

class Teacher:

    def __init__(self, name, gender, birth, course):
        self.name = name
        self.gender = gender
        self.birth = birth
        self.course = course

    def teaching(self):
        print('teaching.....',self.course.name)

p1 = Teacher('laowang', 'Male',
             BirthDate('1995', '1', '27'),
             Course('Python', '28000', '5 months')
             )

print(p1.birth.year, p1.birth.month, p1.birth.day)
print(p1.course.name, p1.course.price, p1.course.period)
D:installpython3python.exe D:/pyscript/test/test.py
1995 1 27
Python 28000 5 months

Process finished with exit code 0