了解python类的继承

时间:2016-08-17 01:14:44

标签: python class

所以我试图了解如何在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中运行。

1 个答案:

答案 0 :(得分:2)

您的代码有三个主要问题

  1. __int__更改为__init__。您的实例未初始化,这就是您收到no attribute 'speed'错误的原因。

  2. 您的子类(继承的类,在本例中为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
    
  3. 现在,在创建实例时,您只需要创建子类的实例。它将继承超类中的方法:

    hero = Player('Ben', 'm', 30)
    
  4. 通过这些更改,这些行:

    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方法。