Reputation: 3
The code is:
Offers = [0, 13, 4]
class Shop:
def __init__(self, item, price, count):
self.item = item
self.price = price
self.count = count
def CreateNew(self):
Offers.append(self.item)
Shop.CreateNew(3)
Why does it happen? I've been wasting hours searching for an solution, no result.
The error occurs at:
Offers.append(self.item)
Upvotes: 0
Views: 1782
Reputation: 1
Offers = [0, 13, 4]
class Shop:
def __init__(self, item, price, count):
self.item = item
self.price = price
self.count = count
def CreateNew(self):
Offers.append(self.item)
p1 = Shop(3, 20, 7)
p1.CreateNew()
print(Offers)
output = [0, 13, 4, 3]
the way you are calling the method is incorrect. you need to pass the parameters to the Class then your methods can access it when you make a call. hope this helps!
Upvotes: 0
Reputation: 2428
Are you thinking something like this?
Offers = [0, 13, 4]
class Shop:
def __init__(self, item, price, count):
self.item = item
self.price = price
self.count = count
def CreateNew(self):
Offers.append(self.item)
# Create new shop object
# Giving None for your price and count, since you don't have them in your example
s = Shop(3, None, None)
# Call objects method
s.CreateNew()
Or if you want to use CreateNew as a class method you can call without creating a new object, you can do it like this
Offers = [0, 13, 4]
class Shop:
def __init__(self, item, price=None, count=None):
self.item = item
self.price = price
self.count = count
@classmethod
def CreateNew(cls, item, price, count):
c = cls(item, price, count)
Offers.append(c.items)
return c
# This adds item to Offers list and returs new shop class for you.
Shop.CreateNew(3)
But using class methods (or static methods) is unusual in Python. And perhaps a bit advanced in this context. This approach is more common in for example C#.
Upvotes: 1