[英]Python - create inherited class attribute under condition
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
which can be instantiated like so: 可以像这样实例化:
wine = Color(aroma='80%', body='30%', acidity='35%', flavor='90%', color='Red')
then I want to be able to create specific classes that will inherit WineComponents()
: 那么我希望能够创建将继承
WineComponents()
特定类:
class Color(WineComponents):
def receipe(self):
pass
and also to have its own attributes, under certain conditions, like so: 并在某些条件下具有自己的属性,例如:
class Color(WineComponents):
if self.color == 'Red':
region = 'France'
type = 'Bordeaux'
def receipe(self):
pass
calling the attribute with: 通过以下方式调用属性:
print wine.region
but this does not work: 但这不起作用:
if self.color == 'Red':
NameError: name 'self' is not defined
is there a workaround this? 有解决方法吗?
Here my five pence: 这是我的五便士:
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)
You could do this with a property 你可以用一个属性
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')
Which can be called as this: 可以这样称呼:
>>> wine = Wine(aroma='80%', body='30%', acidity='35%', flavor='90%', color='Red')
>>> wine.region
'France'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.