Python: Examples of many object-oriented applications

Requirement: Print the following content to realize cooperation between people and different dogs.
Zhang San is working.
Guide dogs are guiding the blind.
Zhang San is working.
Drug detection dogs are anti-narcotics.
Zhang San is working.
Police dogs are working.

Let's take a look at how to write the stupid way first

class PoliceDog(object):
    def attack_enemy(self):
        print('警犬正在攻击人')

class BlindDog(object):
    def lead_road(self):
        print('导盲犬正在领路')

class DrugDog(object):
    def drug(self):
        print('缉毒犬正在缉毒')

class Person(object):
    def __init__(self,name):
        self.name = name

    def work_with_dg(self):
        print(self.name,'在工作')
        self.dog.attack_enemy()

    def work_with_bd(self):
        self.dog.lead_road()

    def work_with_dd(self):
        self.dog.drug()

pd = PoliceDog()
p = Person('张三')
p.dog = pd
p.work_with_dg()

bd = BlindDog()
p.dog = bd
p.work_with_bd() # 每加一个狗都需要重新定义一个方法

dd = DrugDog()
p.dog = dd
p.work_with_dd() # 每加一个狗都需要重新定义一个方法

Disadvantages: each additional dog needs to define the corresponding method in the Person class, the code is redundant and the repetition rate is high

Utilize the optimized code of Duo Tai:

# 狗父类
class Dog(object):
    def work(self):
        print('狗在工作')

# 狗子类
class BlindDog(Dog):
    def work(self):
        print('导盲犬正在导盲')

# 狗子类
class DrugDog(Dog):
    def work(self):
        print('缉毒犬正在缉毒')

# 狗子类
class PoliceDog(Dog):
    def work(self):
        print('警犬正在工作')

# 人类
class Person(object):
    def __init__(self, name):
        self.name = name

    def work_with_dog(self):
        print(self.name, '在工作')
        print('self.dog',self.dog)
        if self.dog is not None and isinstance(self.dog,Dog): #满足条件:self.dog不为None,且self.dog是由父类Dog实例化出来的(self.dog相当于狗子类)
            self.dog.work() # 相当于Blinddog().work/DrugDog().work/PoliceDog().work


# 实例对象
p = Person('张三')

bd = BlindDog()
p.dog = bd # Person类中增加狗的属性,使其等于狗的对象bd
p.work_with_dog()

dd = DrugDog()
p.dog = dd # Person类中增加狗的属性,使其等于狗的对象dd
p.work_with_dog()

pd = PoliceDog()
p.dog = pd # Person类中增加狗的属性,使其等于狗的对象pd
p.work_with_dog() 

Guess you like

Origin blog.csdn.net/weixin_42161670/article/details/113464545