I have this so far:
class Wine:
def __init__(self, key):
a = {}
value = []
a.setdefault(key, [])
def addYear(self, value):
a[key].insert(1, value)
def addProd(self, value):
a[key].insert(2, value)
def addCountry(self, value):
a[key].insert(3, value)
def addPrice(self, value):
a[key].insert(4, value)
def __str__(self):
for key, value in a.items():
value = ', '.join(map(str, value))
print("{}, {}".format(key, value))
b = Wine("Bread and Butter Pinot Noir")
b.addYear("2017")
b.addProd("Sonoma County")
b.addCountry("USA")
b.addPrice("30 USD")
b.__str__()
I want the output to look like this:
Bread and Butter Pinot Noir, 2017, Sonoma County, USA, 30 USD
But it says "name 'a' is not defined"
I don't think you understood Classes real well but still you need to use self.attribute to use any attributes inside class functions, here is a code that will give you the required output
class Wine:
def __init__(self, key):
self.a = {}
self.key = key
self.value = []
self.a.setdefault(key, [])
def addYear(self, value):
self.a[self.key].insert(1, value)
def addProd(self, value):
self.a[self.key].insert(2, value)
def addCountry(self, value):
self.a[self.key].insert(3, value)
def addPrice(self, value):
self.a[self.key].insert(4, value)
def __str__(self):
for key, value in self.a.items():
value = ', '.join(map(str, value))
print("{}, {}".format(key, value))
b = Wine("Bread and Butter Pinot Noir")
b.addYear("2017")
b.addProd("Sonoma County")
b.addCountry("USA")
b.addPrice("30 USD")
b.__str__()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.