0

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)
4
  • 1
    Hello and welcome to Stack Overflow. Could you provide full traceback, it is very helpful for troubleshooting. This is in general. And in this case what you try to do? Commented Apr 26, 2022 at 14:11
  • Where do you create an instance of Shop? Also, you call CreateNew with a parameter (3), but the method doesn't accept any arguments (only acts on self). Commented Apr 26, 2022 at 14:11
  • What are you trying to do? Please specify. Commented Apr 26, 2022 at 14:12
  • It happens because self is 3. You called a method on the class without instantiating the class. Commented Apr 26, 2022 at 14:13

2 Answers 2

1

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#.

Sign up to request clarification or add additional context in comments.

Comments

0
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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.