繁体   English   中英

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

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

我正在尝试更多地了解课程和 OOP。

如何让我的Person类使用Entity所有值以及可能不包含在Entity类中的值进行初始化?

例如, PersonSpirit都继承自Entity 但是,只有Person才会有gender 我怎样才能让Person初始化为gender

在那之后,我是否仍然能够像下面所做的那样创建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()

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

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

过渡性地,它看起来像 Py 3.x 的版本(不确定是哪个)允许super()这个简洁版本:

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

一直在使用数据类试验 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