class animals:
def __init__(self):
pass
def has_legs(self, type):
if type == "snake":
print(False)
else:
print(True)
class dog(animals):
def __init__(self):
# This is where the magic happens
animals.__init__(self)
pass
def dog_has_legs(self):
self.has_legs("dog")
bofur = dog()
bofur.dog_has_legs()
bofur.has_legs("snake")
正如Amadan在评论中指出的,类继承是共享类对象的一种良好且一致的方式。下面是一个例子:
结果:
如您所见,类
dog
继承自animals
,因此它可以从animals
类调用函数和其他对象,就好像它们属于dog
类一样。你知道吗首先定义
func
,它在外部定义。然后要在不同的类中引用该函数,请在类中使用相同的
func
现在可以这样称呼它们。你知道吗
相关问题 更多 >
编程相关推荐