2015-05-28 42 views
2

我如何定义既__init__功能的基类和派生抽象类和都self.*在抽象方法可用?例如: Python的抽象方法与它自己的__init__功能

什么是利用了在基类的抽象类的导入函数的正确方法是什么?例如:在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访问。我想DietPizzaself.firstnameself.lastname。我怎样才能做到这一点?

回答

6

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

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

太好了,谢谢你的回答。我会在10分钟内接受我的。 – user2694306

+1

您是否需要指定调用对象和类,即'super(DietPizza,self).__ init __()'? – BoltzmannBrain

+1

@BoltzmannBrain:不在Python 3中,没有。 –

相关问题