一个类中的一个类

2024-05-15 06:21:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在正在使用OOP,我有一个问题,我们可以在一个类中创建一个类吗?例如,一个叫做人类的类能被分成两部分吗(雌性-雄性)?每个阶级(女性-男性)都有自己的状态和行为。你知道吗


Tags: 状态人类oop男性阶级女性雌性雄性
1条回答
网友
1楼 · 发布于 2024-05-15 06:21:19

是的,你可以这样做,但如果你把男性和女性划分成不同的阶级,仅仅继承人类阶级,那就更好了。你知道吗

class Human:
    def __init__(self, height, weight):
        self.height = height
        self.weight = weight

class Male(Human):
    def __init__(self, name):
        Human.__init__(self, height, weight)  # This will inherit every attribute of the parent class.
        self.name = name

class Female(Human):
    ...some more code

相关问题 更多 >

    热门问题