本文介绍了Python类继承:如何使用不在父类中的值初始化子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习有关类和OOP的更多信息.

I'm trying to learn more about classes and OOP.

我如何让我的 Person 类用 Entity 的所有值初始化,而且还使用 Entity 课?

How can I have my Person class initialize with all the values of Entity but also with a value that may not be contained in the Entity class?

例如, Person Spirit 均从 Entity 继承.但是,只有 Person 会具有 gender .我如何让 Person gender 进行初始化?

For example, both Person and Spirit inherit from Entity. However, only a Person would have a gender. How can I have Person initialize with gender as well?

在那之后,我是否仍可以像我在下面完成操作一样创建 Person 的实例并调用 describe()?

After that, would I still be able to create an instance of Person and call describe() in the same way I've done below?

class Entity(object):

    def __init__(self, state, name, age):
        self.state = state
        self.name = name
        self.age = age

class Person(Entity):

    def describe(self):
        print "Identification: %s, %s, %s." % (self.state, self.name, self.age)

class Spirit(Entity):
    pass  # for now

steve = Person("human", "Steve", "23" # can I then list gender here?)
steve.describe()

推荐答案

在子类上创建一个自定义初始化程序,然后通过 super 调用父类的初始化程序:

Create a custom initializer on the sub-class and then call the parent class's initializer via super:

class Person(Entity):
    def __init__(self, state, name, age, gender):
        self.gender = gender
        super(Person, self).__init__(state, name, age)

这篇关于Python类继承:如何使用不在父类中的值初始化子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 09:22