1 combination
The concept of composition: the important way of software reuse in addition to inheritance there is another way, namely: the combination
A combination refers to a class in which an object of another class is used as a data property, called a combination of classes
>>> class Equip: #武器装备类
... def fire (self):
... print (' Release Fire skill ')
...
>>> class Riven: #英雄Riven的类, a hero needs to be equipped and therefore needs to be combined equip class
... camp= ' Noxus '
... def __init__ (self,nickname):
... self.nickname=nickname
... self.equip=equip () #用Equip类产生一个装备, assigning the equip property to the instance
...
>>> R1=riven (' Rui Wen Wen ')
>>> R1.equip.fire () #可以使用组合的类产生的对象所持有的方法
Release Fire skill
1.1 Differences between combinations and inheritance
Combination and inheritance are important ways to make effective use of existing classes of resources. But both concepts and usage scenarios are different,
1. Ways of inheriting
The relationship between the derived class and the base class is established through inheritance, which is a ' Yes ' relationship, such as a horse in a white horse and a human being an animal.
When there are many identical functions between classes, extracting these common functions into a base class is better with inheritance, such as
The professor is a teacher
>>> class Teacher:
... def __init__ (Self,name,gender):
... self.name=name
... self.gender=gender
... def teach (self):
.. print (' teaching ')
...
>>>
>>> class Professor (Teacher):
... pass
...
>>> p1=professor (' Egon ', ' Male ')
>>> P1.teach ()
Teaching
2. Combination of ways
The relationship between classes and classes is established in a combinatorial way, and it is a ' have ' relationship, such as a professor having a birthday,
Professor teaches Python Courses
Class BirthDate:
def __init__ (Self,year,month,day):
Self.year=year
Self.month=month
Self.day=day
Class Couse:
def __init__ (self,name,price,period):
Self.name=name
Self.price=price
Self.period=period
Class Teacher:
def __init__ (Self,name,gender):
Self.name=name
Self.gender=gender
def teach (self):
Print (' teaching ')
Class Professor (Teacher):
def __init__ (Self,name,gender,birth,course):
teacher.__init__ (Self,name,gender)
Self.birth=birth
Self.course=course
P1=professor (' Egon ', ' Male ',
BirthDate (' 1995 ', ' 1 ', ' 27 '),
Couse (' python ', ' 28000 ', ' 4 months '))
Print (P1.birth.year,p1.birth.month,p1.birth.day)
Print (P1.course.name,p1.course.price,p1.course.period)
When there are significant differences between classes, and the smaller classes are the components needed for larger classes, the combination is better.
python\ combination and re-usability