简体   繁体   English

Python 类继承:如何使用不在父类中的值初始化子类

[英]Python Class Inheritance: How to initialize a subclass with values not in the parent class

I'm trying to learn more about classes and OOP.我正在尝试更多地了解课程和 OOP。

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类使用Entity所有值以及可能不包含在Entity类中的值进行初始化?

For example, both Person and Spirit inherit from Entity .例如, PersonSpirit都继承自Entity However, only a Person would have a gender .但是,只有Person才会有gender How can I have Person initialize with gender as well?我怎样才能让Person初始化为gender

After that, would I still be able to create an instance of Person and call describe() in the same way I've done below?在那之后,我是否仍然能够像下面所做的那样创建Person的实例并调用describe()

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()

Create a custom initializer on the sub-class and then call the parent class's initializer via super :在子类上创建自定义初始化程序,然后通过super调用父类的初始化程序:

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

Transitionally, it looks like versions of Py 3.x (not sure which ones) allow this terse version of super() :过渡性地,它看起来像 Py 3.x 的版本(不确定是哪个)允许super()这个简洁版本:

def __init__(self, state, name, age, gender):
        self.gender = gender
        # Prototype initialization 3.x:
        super().__init__(state, name, age)

Been experimenting with SQLAlchemy models using dataclasses, so when I zipped on by looking at all things Python inheritance, I felt this might extend the answer:一直在使用数据类试验 SQLAlchemy 模型,所以当我通过查看 Python 继承的所有内容进行压缩时,我觉得这可能会扩展答案:

from dataclasses import dataclass

@dataclass
class Entity():
    state: str
    name: str
    age: int

@dataclass
class Person(Entity):
    gender: str

    def describe(self):
        print("State: {state}, Name: {name}, Age: {age}, Gender: {gender}"
            .format(state=self.state, name=self.name, age=self.age, gender=self.gender))

man = Person("human", "humanname", 21, "cisgendered")

man.describe()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM