Relationships between classes like python

In our world, there are always some relations between things. In object-oriented, there are also relations between classes

1. Dependency
When performing an action, you need xxx to help you complete the action. At this time, the relationship is the lightest. You can change another thing at any time to complete the operation

  

class Person:
    def play(self, tools):
        tools.run()
        print('Finally, we can play games')

class Computer:
    def run(self):
        print('The computer is turned on,DNF Landed')
class Phone:
    def run(self):
        print('The glory of the king has landed')
c = Computer()
PH = Phone()
p = Person()
p.play(c)
# The computer is turned on,DNF Landed
# Finally, we can play games
p.play(PH)
# The glory of the king has landed
# Finally, we can play games

2. Relationship
Burying objects in objects
1. One to one relationship
    

class Boy:

    def __init__(self, name,  girlFriend=None):
        # During initialization, you can set the properties of one object to the objects of another class
        self.girlFriend = girlFriend  # A boy has a girlfriend

    def chi(self):
        if self.girlFriend:
            print(f"With his girlfriend{self.girlFriend.name}Go to eat")
        else:
            print("Single dog, What to eat?? Roll to learn.")

    def movie(self):
        if self.girlFriend:
            print(f"With his girlfriend{self.girlFriend.name}Go to see the films")
        else:
            print("Single dog, What to see? Roll to learn.")


class Girl:
    def __init__(self, name):
        self.name = name

b = Boy("Bao Lang")
g = Girl("ABC")
b.chi()  # Single dog, What to eat?? Roll to learn.

# alex I introduced a girl friend to Bao Lang.
b.girlFriend = g
b.chi() # With his girlfriend ABC Go to eat

g2 = Girl("QWER")
b.girlFriend = g2 # Changed a girlfriend
b.chi() # With his girlfriend QWER Go to eat

 

2. One to many relationship
    

# One to many
class School:
    def __init__(self, name):
        self.teach_list = []
    def zhaopin(self,teach):
        self.teach_list.append(teach)
    def shagnke(self):
        for t in self.teach_list:
            t.work()
class Teacher:
    def   __init__(self, name):
        self.name = name
    def work(self):
        print(f'{self.name}At school')
x = School('xxx School')
t1 = Teacher('Teacher 1')
t2 = Teacher('Teacher 2')
t3 = Teacher('Teacher 3')
t4 = Teacher('Teacher 4')

x.zhaopin(t1)
x.zhaopin(t2)
x.zhaopin(t3)
x.zhaopin(t4)

x.shagnke()
'''
//Teacher 1 in class
//Teacher 2 in class
//Teacher 3 in class
//Teacher 4 in class
'''

Relationship in class: dependency is the lightest. Inheritance is the most important. Association is more subtle

Keywords: Python

Added by grissom on Wed, 04 Dec 2019 12:42:26 +0200