(问答题)
使用类完成
妈妈长得很漂亮,爸爸iq很高,儿子继承了他们有优良基因,并且还弹得一手好钢琴。
#!/sur/bin/nve python
# coding: utf-8
class Dad:
IQ = 'High(100)'
def __init__(self, name):
self.NAME = name
def show(self):
print(f"\nName: {self.NAME}\nIQ: {self.IQ}")
class Mom:
FACE = 'Pretty'
def __init__(self, name):
self.NAME = name
def show(self):
print(f"\nName: {self.NAME}\nFace: {self.FACE}")
class Son(Dad, Mom):
LONG = 'He play paino is well!'
def __init__(self, name):
self.NAME = name
def show(self):
print(f"\nName: {self.NAME}\nIQ: {self.IQ}\nFace: {self.FACE}\nLong: {self.LONG}")
if __name__ == '__main__':
dad = Dad('Bob')
mom = Mom('Rose')
son = Son('Tom')
dad.show()
mom.show()
son.show()
class Mother:
def __init__(self):
self.beauty = 100
class Father:
def __init__(self):
self.IQ = 200
class Son(Mother, Father):
def play_piano(self):
print("I can play the piano!")
son = Son()
print("Son的美丽指数:", son.beauty)
print("Son的智商:", son.IQ)
son.play_piano()
不知道你这个问题是否已经解决, 如果还没有解决的话: ##可变关键字传参举例:
def showconfig(**kwargs):
for k,v in kwargs.items();
print(’{}={}‘.format(k,v),end=',')
showconfig(a=23,b=32,c='1331',d='adafas')#输出都是字典 {'a':23,'b':32,'c':'1331'}
import random
from PIL import Image
class Male:
def __init__(self):
self.appearance = "Inherit from mother"
self.intelligence = "Inherit from father"
def play_piano(self):
print("I can play piano!")
class Son(Male):
def __init__(self):
super().__init__()
def play_piano(self):
super().play_piano()
print("Also, I can play piano!")
在这个代码示例中,我们先定义了一个Male类,该类具有属性appearance和intelligence,分别代表外貌和智力,这些属性通过继承母亲和父亲的基因获得。
然后我们定义了一个Son类,该类继承了Male类,并且扩展了play_piano方法。通过调用super().play_piano(),我们保留了父类的play_piano行为,并在其基础上添加了新的行为。
这样,Son类就同时继承了母亲的容貌和父亲的智力,并且具备弹奏钢琴的能力。