python 类继承和组合_Python:继承与组合

从父母那里生孩子或从父母那里生孩子肯定是不好的。

正确的方法是创建一个基类,比如Person,并从中继承子类和父类。

这样做的一个优点是消除代码重复,此时只有firstname/lastname字段复制到这两个对象中,但是您可能有更多的数据或其他方法(如get_name())来处理这些数据。

下面是一个例子: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对象(相对于父对象和子对象)。

跟踪家庭状态和父母/子女的功能可以移动到另一个对象中。

下面是一个例子: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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值