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):
        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()
# The computer is turned on,DNF Landed
# Finally, we can play games
# 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{}Go to eat")
            print("Single dog, What to eat?? Roll to learn.")

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

class Girl:
    def __init__(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):
    def shagnke(self):
        for t in self.teach_list:
class Teacher:
    def   __init__(self, name): = name
    def work(self):
        print(f'{}At school')
x = School('xxx School')
t1 = Teacher('Teacher 1')
t2 = Teacher('Teacher 2')
t3 = Teacher('Teacher 3')
t4 = Teacher('Teacher 4')


//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