python 类继承和组合_Python:继承与组合
從父母那里生孩子或從父母那里生孩子肯定是不好的。
正確的方法是創(chuàng)建一個基類,比如Person,并從中繼承子類和父類。
這樣做的一個優(yōu)點是消除代碼重復,此時只有firstname/lastname字段復制到這兩個對象中,但是您可能有更多的數(shù)據(jù)或其他方法(如get_name())來處理這些數(shù)據(jù)。
下面是一個例子:class Person(object):
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
def get_name(self):
return '%s %s' % (self.firstname, self.lastname)
class Parent(Person):
def __init__(self, firstname, lastname):
super(Parent, self).__init__(firstname, lastname)
self.kids = []
def havechild(self, firstname):
print self.firstname, "is having a child"
self.kids.append(Child(self, firstname))
class Child(Person):
def __init__(self, parent, firstname):
super(Child, self).__init__(firstname, parent.lastname)
self.parent = parent
另一種方法是在沒有繼承的情況下進行,但是只有一個Person對象(相對于父對象和子對象)。
跟蹤家庭狀態(tài)和父母/子女的功能可以移動到另一個對象中。
下面是一個例子:from collections import defaultdict
class Person(object):
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
def get_name(self):
return '%s %s' % (self.firstname, self.lastname)
class FamilyRegistry(object):
def __init__(self):
self.kids = defaultdict(list)
def register_birth(self, parent, child_name):
print parent.firstname, "is having a child"
child = Person(child_name, parent.lastname)
self.kids[parent.lastname].append(child)
return child
def print_children(self, person):
children = self.kids[person.lastname]
if len(children) == 0:
print '%s has no children' % person.get_name()
return
for child in children:
print child.get_name()
它的工作原理如下:joe = Person('Joe', 'Black')
jill = Person('Jill', 'White')
registry = FamilyRegistry()
registry.register_birth(joe, 'Joe Junior') # Joe is having a child
registry.register_birth(joe, 'Tina') # Joe is having a child
registry.print_children(joe) # Joe Junior Black
# Tina Black
registry.print_children(jill) # Jill White has no children
總結(jié)
以上是生活随笔為你收集整理的python 类继承和组合_Python:继承与组合的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python renames_Pytho
- 下一篇: 新飞电器复工最新消息 高管团队已确定