Python - 在条件下创建继承的class属性

时间:2017-08-09 18:39:43

标签: python class attributes

class WineComponents(object):

    def __init__(self, aroma, body, acidity, flavor, color):
        self.aroma = aroma
        self.body = body
        self.acidity = acidity
        self.flavor = flavor
        self.color = color

可以像这样实例化:

wine = Color(aroma='80%', body='30%', acidity='35%', flavor='90%', color='Red')

然后我希望能够创建将继承WineComponents()的特定类:

class Color(WineComponents): 

      def receipe(self):
          pass

并且在某些条件下也有自己的属性,如下所示:

class Color(WineComponents):

     if self.color == 'Red':
        region  = 'France'
        type = 'Bordeaux'

     def receipe(self):
         pass

使用:

调用属性
print wine.region

但这不起作用:

 if self.color == 'Red':
NameError: name 'self' is not defined

有解决方法吗?

2 个答案:

答案 0 :(得分:0)

这是我的五便士:

class WineComponents(object):

def __init__(self, aroma, body, acidity, flavor, color):
    self.aroma = aroma
    self.body = body
    self.acidity = acidity
    self.flavor = flavor
    self.color = color


class Color(WineComponents):
    def __init__(self, aroma, body, acidity, flavor, color):
        super(Color, self).__init__(aroma, body, acidity, flavor, color)
        if self.color == 'Red':
            self.region = 'France'
            self.type = 'Bordeaux'

    def receipe(self):
        pass

if __name__ == '__main__':
    wine = Color(aroma='80%', body='30%', acidity='35%', flavor='90%', 
    color='Red')
    print (wine.region, wine.type)

答案 1 :(得分:0)

您可以使用属性

执行此操作
class Wine(object):
    def __init__(self, aroma, body, acidity, flavor, color):
        self.aroma = aroma
        self.body = body
        self.acidity = acidity
        self.flavor = flavor
        self.color = color

    @property
    def region(self):
        if self.color == 'Red':
            return 'France'
        else:
            raise NotImplementedError('unknown region for this wine')

可以这样称呼:

>>> wine = Wine(aroma='80%', body='30%', acidity='35%', flavor='90%', color='Red')
>>> wine.region
'France'