我试图从两个父对象生成一个子类,它是作为其和/减运算构建的。我将尝试用一个简单的例子来最好地解释
图片我有以下父类
class UpperBody():
def __init__(self, owner='John', age=25, max_lifting_weight=100):
self.owner=owner # Identifier, who "owns" this upper body
self.age=age # Second identifier
self.max_lifting_weight=max_lifting_weight
def __add__(self, other):
#__sub__ would be equivalent
if other.age!=self.age:
raise AttributeError('You cannot add body parts with different ages!')
if other.owner!=self.owner:
print('This does not seem to fit here, but alright...')
return UpperBody(self.owner + '_' + other.owner, self.age, self.max_lifting_weight + other.max_lifting_weight)
return UpperBody(self.owner, self.age, self.max_lifting_weight + other.max_lifting_weight)
def can_lift(self, weight):
# Returns boolean
return weight < self.max_lifting_weight
class LowerBody():
def __init__(self, owner='John', age=25, max_lifting_weight=100):
self.owner=owner # Identifier, who "owns" this lower body
self.age=age # Second identifier
self.max_lifting_weight=max_lifting_weight
def __add__(self, other):
#__sub__ would be equivalent
if other.age!=self.age:
raise AttributeError('You cannot add body parts with different ages!')
if other.owner!=self.owner:
print('This does not seem to fit here, but alright...')
return UpperBody(self.owner + '_' + other.owner, self.age, self.max_lifting_weight + other.max_lifting_weight)
return UpperBody(self.owner, self.age, self.max_lifting_weight + other.max_lifting_weight)
def can_lift(self, weight):
# Legs are stronger
return weight < self.max_lifting_weight * 1.2
我想通过添加两个父类来生成人类子类。诸如此类的东西
class Human(UpperBody, LowerBody):
def __init__(self, name, age, max_lifting_weight_upper, max_lifting_weight_lower):
self.name=name
self.age=age
# From here on, I have no clue how to follow. This does not load to "self", obviously.
UpperBody.__init__(name, age, max_lifting_weight_upper) + LowerBody.__init__(name, age, max_lifting_weight_upper)
然后访问父类中定义的方法,如can\u lift
我能想出的最好办法就是通过函数
def HumanConstructor(UpperBody, LowerBody):
return UpperBody + LowerBody
然而,如果人类类有额外的方法,这将不会有多大帮助。有没有办法做到这一点
事先谢谢
您基本上只需要正确初始化Human类中的子类:
相关问题 更多 >
编程相关推荐