Object-oriented: space issues like the relationship between classes

1.1 Where can add object properties

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

    def func(self,sex):
        self.sex = sex
类外面可以:
obj = A('barry')
obj.age = 18
print(obj.__dict__)  # {'name': 'barry', 'age': 18}

类内部也可以:
obj = A('barry') # __init__方法可以。
obj.func('男')  # func 方法也可以。

** Summary: attributes of the objects which can not only __init__ added, may be added to the outside of the other class or classes of methods. **

1.2 Where can add static properties of the class

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

    def func(self,sex):
        self.sex = sex
    
    def func1(self):
        A.bbb = 'ccc'
类的外部可以添加

A.aaa = 'taobao'
print(A.__dict__)

类的内部也可以添加。

A.func1(111)
print(A.__dict__)

Summary: The properties of the class not only within the class is added, can also be added outside the class.

1.3 How to find the object properties of the class

Instantiate an object class attributes can be found by means of point

By way of illustration:

img

Find the object attribute order: first from object space to find ------> class space to find ------> ------- parent find space> .....

Find the class name attribute order: start looking for this type of space -------> -------- find the parent class space> ........

The above sequence is irreversible way, the class name can not find the object's properties.

II. The relationship between class and class

Zoomed thousands of the world, there are rules and laws among all things. Classes and objects are all things in the zoomed thousands of the world into ⾏ classification. There is a corresponding relationship between those things. The same is true between classes. the presence of the following classes and class relations in the world ⾯ to object:

. \ 1 dependencies
\ 2 relationship.
\ 3 combinational relationship.
\ 4-aggregation relationship.
\ 5 implements relationship.
\ 6 inheritance. (One of the three categories of characteristics: inheritance.)

2.1 Dependencies

Therefore especially First, the design has a scene. Like zoomed should install refrigerator. Note In this scenario, the fact is there is two things. ⼀ is a zoomed image, zoomed as those responsible for control of the entire event, as well as a ⼀ refrigerator, freezer is responsible zoomed image manipulation.

Therefore especially First, to write two classes, one is zoomed ⼀ object class, a refrigerator based ⼀

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

    def open(self):
        '''
        开⻔
        '''
        pass
    
    def close(self):
        '''
        关⻔
        '''
        pass


class Refrigerator:
    
    def open_door(self):
        print("冰箱⻔被打开了")
    
    def close_door(self):
        print("冰箱⻔被关上了")

  冰箱的功能非常简单, 只要会开⻔, 关⻔就⾏了. 但是⼤象就没那么简单了. 想想. ⼤象开⻔和关⻔的时候是不是要先找个冰箱啊. 然后呢? 打开冰箱⻔. 是不是打开刚才找到的那个冰箱⻔. 然后装⾃⼰. 最后呢? 关冰箱⻔, 注意, 关的是刚才那个冰箱吧. 也就是说. 开⻔和关⻔⽤的是同⼀个冰箱. 并且. ⼤象有更换冰箱的权利, 想进那个冰箱就进那个冰箱. 这时, ⼤象类和冰箱类的关系并没有那么的紧密. 因为⼤象可以指定任何⼀个冰箱. 接下来. 把代码完善⼀下.

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

    def open(self,obj1):
        '''
        开⻔

        '''
        print('大象要开门了,默念三声,开')
        obj1.open_door()

    def close(self):
        '''
        关⻔
        '''
        print('大象要关门了,默念三声,关')


class Refrigerator:

    def open_door(self):
        print("冰箱⻔被打开了")

    def close_door(self):
        print("冰箱⻔被关上了")


elphant1 = Elphant('大象')
haier = Refrigerator()
elphant1.open(haier)

动作发起的主体是大象,依赖关系:将一个类的对象或者类名传到另一个类的方法使用。此时, , ⼤象和冰箱之间就是依赖关系. 我⽤着你. 但是你不属于我. 这种关系是最弱的.比如. 公司和雇员之间. 对于正式员⼯, 肯定要签订劳动合同. 还得⼩⼼伺候着. 但是如果是兼职. 那⽆所谓. 需要了你就来. 不需要你就可以拜拜了. 这⾥的兼职(临时⼯) 就属于依赖关系.我⽤你. 但是你不属于我

2.2 关联,聚合,组合关系

其实这三个在代码上写法是⼀样的. 但是, 从含义上是不⼀样的.

\1. 关联关系. 两种事物必须是互相关联的. 但是在某些特殊情况下是可以更改和更换的.

\2. 聚合关系. 属于关联关系中的⼀种特例. 侧重点是xxx和xxx聚合成xxx. 各⾃有各⾃的声明周期. 比如电脑. 电脑⾥有CPU, 硬盘, 内存等等. 电脑挂了. CPU还是好的. 还是完整的个体

\3. 组合关系. 属于关联关系中的⼀种特例. 写法上差不多. 组合关系比聚合还要紧密. 比如⼈的⼤脑, ⼼脏, 各个器官. 这些器官组合成⼀个⼈. 这时. ⼈如果挂了. 其他的东⻄也跟着挂了

先看关联关系:

这个最简单. 也是最常⽤的⼀种关系. 比如. ⼤家都有男女朋友. 男⼈关联着女朋友. 女⼈关联着男朋友. 这种关系可以是互相的, 也可以是单⽅⾯的.

class Boy:
    def __init__(self,name,girlFriend=None):
        self.name = name
        self.girlFriend = girlFriend

    def have_a_diner(self):
        if self.girlFriend:
            print('%s 和 %s 一起晚饭'%(self.name,self.girlFriend))
        else:
            print('单身狗,吃什么饭')


class Girl:
    def __init__(self,name):
        self.name = name
b = Boy('日天')
b.have_a_diner() # 此时是单身狗

# 突然有一天,日天牛逼了
b.girlFriend = '如花'
b.have_a_diner()  #共进晚餐
wu 生下来就有女朋友 服不服
gg = Girl('小花')
bb = Boy('wu', gg)
bb.have_a_diner()

结果嫌他有点娘,不硬,分了
bb.girlFriend = None
bb.have_a_diner()

Note that this time is the relationship between the two classes Boy and Girl. Two classes of objects closely practicing which ⼀ a no. For another time on a very, very lonely. Relationship, in fact, I need you. You I also belong. this is the relationship. this relationship has, like many, many, such as the relationship between the school and the teacher.

老师属于学校,必须有学校才可以工作
class School:

    def __init__(self,name,address):
        self.name = name
        self.address = address


class Teacher:

    def __init__(self,name,school):
        self.name = name
        self.school = school

s1 = School('北京校区','美丽的沙河')
s2 = School('上海校区','上海迪士尼旁边')
s3 = School('深圳校区','南山区')

t1 = Teacher('武大',s1)
t2 = Teacher('海峰',s2)
t3 = Teacher('日天',s3)

print(t1.school.name)
print(t2.school.name)
print(t3.school.name)

But the school also depends on the teacher, so the teacher school should depend on each other.

class School:

    def __init__(self,name,address):
        self.name = name
        self.address = address
        self.teacher_list = []

    def append_teacher(self,teacher):
        self.teacher_list.append(teacher)
        
class Teacher:

    def __init__(self,name,school):
        self.name = name
        self.school = school

s1 = School('北京校区','美丽的沙河')
s2 = School('上海校区','上海迪士尼旁边')
s3 = School('深圳校区','南山区')

t1 = Teacher('武大',s1)
t2 = Teacher('海峰',s2)
t3 = Teacher('日天',s3)

s1.append_teacher(t1)
s1.append_teacher(t2)
s1.append_teacher(t3)

print(s1.teacher_list)
for teacher in s1.teacher_list:
    print(teacher.name)

Okay. This is the relationship. When appears on the logic. I need you. You have to belong to me. This is a logical relationship. That attention. Closeness of this relationship to be tighter than on the screen for dependencies multi As Combined and polymerization relationship, in fact, not very different code, with regard to the combination of example:

Combination: a class object is encapsulated into another attribute of the object class, called combination.

Design a game character class, make a few instances of these objects allow game characters to achieve melee results.

class Gamerole:
    def __init__(self,name,ad,hp):
        self.name = name
        self.ad = ad
        self.hp = hp
    def attack(self,p1):
        p1.hp -= self.ad
        print('%s攻击%s,%s掉了%s血,还剩%s血'%(self.name,p1.name,p1.name,self.ad,p1.hp))
gailun = Gamerole('盖伦',10,200)
yasuo= Gamerole('亚索',50,80)

#盖伦攻击亚索
gailun.attack(yasuo)
# 亚索攻击盖伦
yasuo.attack(盖伦)

But this does not mean to attack each other, the general war game like manner to the aid of weapons, weapon is a class, object class contains a lot of weapons: a sword stick sword ax hook fork and so on, so write a weapon class.

class Gamerole:
        def __init__(self,name,ad,hp):
            self.name = name
            self.ad = ad       
            self.hp = hp    
        def attack(self,p1):        
            p1.hp -= self.ad        
            print('%s攻击%s,%s掉了%s血,还剩%s血'%(self.name,p1.name,p1.name,self.ad,p1.hp))
class Weapon:    
        def __init__(self,name,ad):        
            self.name = name        
            self.ad = ad   
        def weapon_attack(self,p1,p2):       
            p2.hp = p2.hp - self.ad - p1.ad       
            print('%s 利用 %s 攻击了%s,%s还剩%s血' %(p1.name,self.name,p2.name,p2.name,p2.hp))

Next With weapons to attack each other:

pillow = Weapon('绣花枕头',2)
pillow.weapon_attack(barry,panky)
#但是上面这么做不好,利用武器攻击也是人类是动作的发起者,所以不能是pillow武器对象,而是人类利用武器攻击对方

So, modify the code.

class Gamerole:
    def __init__(self,name,ad,hp):
        self.name = name
        self.ad = ad
        self.hp = hp
    def attack(self,p1):
        p1.hp -= self.ad
        print('%s攻击%s,%s掉了%s血,还剩%s血'%(self.name,p1.name,p1.name,self.ad,p1.hp))
        
    def equip_weapon(self,wea):
        self.wea = wea  # 组合:给一个对象封装一个属性改属性是另一个类的对象
class Weapon:
    def __init__(self,name,ad):
        self.name = name
        self.ad = ad
    def weapon_attack(self,p1,p2):
        p2.hp = p2.hp - self.ad - p1.ad
        print('%s 利用 %s 攻击了%s,%s还剩%s血'
              %(p1.name,self.name,p2.name,p2.name,p2.hp))


# 实例化三个人物对象:
barry = Gamerole('五大',10,200)
panky = Gamerole('金莲',20,50)
pillow = Weapon('绣花枕头',2)

# 给人物装备武器对象。
barry.equip_weapon(pillow)

# 开始攻击
barry.wea.weapon_attack(barry,panky)

Is a combination of the above, as long as the person .equip_weapon this method, then the characters on the object encapsulates a weapon, and then use their weapons object to call weapon_attack method class.

Guess you like

Origin www.cnblogs.com/sundawei7/p/11304519.html