python - Python:从减法/加法构造一个类
问题描述
我正在尝试从两个父母生成一个子类,它是作为其和/减法构建的。我将尝试用一个简单的例子来最好地解释。
图片我有以下父类。
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
我想通过添加两个父类来生成Human子类。诸如此类的东西,
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_lift之类的方法。
我能想到的最好的办法就是通过一个函数,因此,
def HumanConstructor(UpperBody, LowerBody):
return UpperBody + LowerBody
但是,如果Human类有额外的方法,这将无济于事。¿ 有没有办法做到这一点?
预先感谢!
解决方案
您基本上只需要正确初始化 Human 类中的子类:
class Human(UpperBody, LowerBody):
def __init__(self, name, age, max_lifting_weight_upper, max_lifting_weight_lower):
self.name=name
self.age=age
# create the child class instances
UpperBody.__init__(name, age, max_lifting_weight_upper)
LowerBody.__init__(name, age, max_lifting_weight_upper)
def do_something(self):
UpperBody.can_lift()
LowerBody.can_lift()
推荐阅读
- arrays - 我该如何解决这个动态规划问题(获胜策略)?
- php - 大写表单输入中的第一个字母 - Laravel
- python - seaborn barplot 为色调添加 xticks
- android - Google Play 游戏、备份数据、不推荐使用云端硬盘
- android - 沉浸式模式活动转换
- hibernate - Spring Boot:在测试中添加@Transcational会使测试失败,否则通过
- javascript - 使用 tab 键进行页面导航时,滚动到表单元素上的错误消息
- django - 如何清除ckeditor django中的输入格式?
- javascript - 当页面上的另一个视频正在播放时禁用 videoElements
- laravel - 如何安装 Laravel 6.x UI 组件?