python - 如何在子类中调用父类?

标签 python class python-3.x methods subclass

我需要创建一个对 Plant 的 UNBOUND 方法调用来设置名称和叶子,但我不知道如何操作。感谢您的帮助。

我的代码:

class Plant(object):
    def __init__(self, name : str, leaves : int):
        self.plant_name = name
        self.leaves = leaves
    def __str__(self):
        return "{} {}".format(self.plant_name, self.leaves)
    def __eq__(self, plant1):
        if self.leaves == plant1.leaves:
            return self.leaves
    def __It__(self, plant1):
        if self.leaves < plant1.leaves:
            print ("{} has more leaves than {}".format(plant1.plant_name, self.plant_name))
            return self.leaves < plant1.leaves
        elif self.leaves > plant1.leaves:
            print ("{} has more leaves than {}".format(self.plant_name, plant1.plant_name))
            return self.leaves < plant1.leaves

class Flower(Plant):
    def __init__(self, color : str, petals : int):
        self.color = color
        self.petals = petals

    def pick_petal(self.petals)
        self.petals += 1

作业的准确措辞:

Create a new class called Flower. Flower is subclassed from the Plant class; so besides name, and leaves, it adds 2 new attributes; color, petals. Color is a string that contains the color of the flower, and petal is an int that has the number of petals on the flower. You should be able to create an init method to setup the instance. With the init you should make an UNBOUND method call to plant to setup the name and leaves. In addition, create a method called pick_petal that decrements the number of petals on the flower.

最佳答案

“未绑定(bind)方法调用”意味着您在类上而不是在类的实例上调用方法。这意味着类似于 Plant.some_method

在此上下文中唯一有意义的未绑定(bind)调用是调用基类的 __init__ 方法。这似乎满足了“设置名称和叶子”的要求,也是过去常见的继承方式。

看起来像这样:

class Flower(Plant):
    def __init__(self, name, leaves, color, petals):
        Plant.__init__(self, ...)
        ...

您需要将适当的参数传递给 __init__。第一个是self,其余由基类中的Plant.__init__定义。您还需要修复参数列表的语法,因为 `color : str' 不是有效的 python。


注意:一般来说,更好的解决办法是调用super而不是在父类 __init__ 上执行未绑定(bind)的方法调用。不过,我不确定你能用这个建议做什么。也许导师让你先继承旧的方式,然后再学习新的方式?

对于此作业,您可能应该使用 Plant.__init__(...),因为这是作业明确要求您执行的操作。您可能会跟进讲师,询问有关 super 的信息。

关于python - 如何在子类中调用父类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36920092/

相关文章:

python - 从 bash 到 GO 服务器的 REST post 查询有效但对于 Python 失败

c# - 使类在程序集之外不可见

python - 为什么Python没有 "continue if"语句?

python - 查找列表中连续项目的索引

python - 为什么对象没有 hasattr 和 getattr 作为属性?

mysql - 使用sqlalchemy同时执行多条sql语句

python - 对列中的数据进行求和和计数

python - 为具有计算值 NetworkX 的图形编写标题

python - Qwidget 背景颜色改变时程序随机崩溃

c++ - 想要创建自己的类 String