所以我试图了解如何在python中构建子类。
所以我创建了一个perent和一个子类,但我不知道如何让它们工作
所以这是我目前的代码
from abc import ABCMeta, abstractmethod
class Persion(object):
__metaclass__ = ABCMeta # sets the metaclass to a abstract base class . that means we never call this class directley insted its used for child classes to inhearrit
def __init__(self, name, gender):
self.name = name
self.gender = gender
def talk(self):
print("hi my name is " + self.name + " and I am a " + self.gender + ".")
@abstractmethod
def PersionType(self):
"""Returns a string of the childs type"""
pass
class Player(Persion):
def __int__(self,speed):
self.name = name
self.gender = gender
self.speed = speed
self.posX = 0
self.posY = 0
def moveXY(self, X, Y):
self.posX = X
self.posY = Y
def PersionType(self):
return 'Player'
player=Persion("Ben","m")
hero = Player(player,30)
hero.moveXY(20,20)
print("you are now at ", hero.posX, "," , hero.posY)
print("your speed is ", hero.speed)
print("your gender is ", hero.gender)
hero.talk()
所以最终结果是我希望这些功能起作用。 但是有些东西已经成为了我想要找到的东西。
hero.moveXY(20,20)
print("you are now at ", hero.posX, "," , hero.posY)
print("your speed is ", hero.speed)
print("your gender is ", hero.gender)
hero.talk()
我的错误sutch as
line 36, in <module>
print("your speed is ", hero.speed)
AttributeError: 'Player' object has no attribute 'speed'
我这样做是为了帮助我理解inheratince如何在python中运行。
答案 0 :(得分:2)
您的代码有三个主要问题:
将__int__
更改为__init__
。您的实例未初始化,这就是您收到no attribute 'speed'
错误的原因。
您的子类(继承的类,在本例中为Player
)应该有一个__init__
方法,该方法接受您想要的所有参数。您可以将超类(Persion
)使用的那些传递给超类的__init__
。这意味着可能将__init__
方法更改为:
class Player(Persion):
def __init__(self, name, gender, speed):
super(Player, self).__init__(name, gender)
self.speed = speed
self.posX = 0
self.posY = 0
现在,在创建实例时,您只需要创建子类的实例。它将继承超类中的方法:
hero = Player('Ben', 'm', 30)
通过这些更改,这些行:
print("you are now at ", hero.posX, "," , hero.posY)
print("your speed is ", hero.speed)
print("your gender is ", hero.gender)
hero.talk()
现在生成此输出:
you are now at 20 , 20
your speed is 30
your gender is m
hi my name is Ben and I am a m.
其他小笔记:
Person
而不是Persion
。@abstractmethod
方法。