【问题标题】:Python Abstract Method With It's own __init__ function [duplicate]具有自己的__init__函数的Python抽象方法[重复]
【发布时间】:2015-08-11 09:34:25
【问题描述】:

如何在基类和派生抽象类中定义__init__ 函数,并使所有self.* 在抽象方法中可用?例如:

使用在抽象类的基类中导入的函数的正确方法是什么?例如:在 base.py 我有以下内容:

import abc

class BasePizza(object):
    __metaclass__  = abc.ABCMeta
    def __init__(self):
        self.firstname = "My Name"

    @abc.abstractmethod
    def get_ingredients(self):
         """Returns the ingredient list."""

然后我在diet.py中定义方法:

import base

class DietPizza(base.BasePizza):
    def __init__(self):
        self.lastname = "Last Name"

    @staticmethod
    def get_ingredients():
        if functions.istrue():
            return True
        else:
            return False

但是,当我运行 diet.py 时,我只能访问 self.lastname。我希望DietPizza 同时拥有self.firstnameself.lastname。我该怎么做?

【问题讨论】:

    标签: python python-3.x abstract-class abc


    【解决方案1】:

    你的BasePizza.__init__是一个具体的方法;只需使用super() 调用它:

    class DietPizza(BasePizza):
        def __init__(self):
            super().__init__()
            self.lastname = "Last Name"
    

    【讨论】:

    • 太好了,感谢您的回答。他们让我在 10 分钟内接受。
    • 不需要指定调用对象和类,即super(DietPizza, self).__init__()
    • @BoltzmannBrain:不是在 Python 3 中,不是。
    • @MartijnPieters touché,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2011-05-21
    • 2018-05-12
    • 2016-05-04
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    相关资源
    最近更新 更多