-1
class Items():
    def Bucket(self):
        self.cost(5)

print(Items.Bucket()) # I want this to return the cost of the item

I want this to print the cost of the item listed. In this case a bucket which i want it to return 5. Right now it returns...

TypeError: Bucket() missing 1 required positional argument: 'self'

Any suggestions?

2 Answers2

2

The reason why you are getting this error is because your Bucket method is defined as an instance method, and you are trying to call it as a class method.

I suggest you read this here about the difference between class methods and instance methods. Which will also explain how self plays a role here.

To make an instance of Items, you need to call it:

items_obj = Items()

Now, you have an instance of the Items class, and can now properly call your method Bucket:

items_obj.Bucket()

It seems like you are already calling a method inside your Bucket method called cost. So, assuming that this method simply returns the cost then just return calling self.cost(5) in your Bucket method:

def Bucket(self):
    return self.cost(5)

So, you should have as a final solution:

class Items:
    def Bucket(self):
        return self.cost(5)

items_obj = Items()
print(items_obj.Bucket())

Note: You don't need to have () when defining your class. Assuming you are using Python 3, you can just define your class as: class Items: as indicated above.

Also, it would be good to conform to good style practice in your code, by taking a look at the style-guide here: https://www.python.org/dev/peps/pep-0008/

Community
  • 1
  • 1
idjaw
  • 25,487
  • 7
  • 64
  • 83
0

Try this:

class Items():
    def __init__(self,cost):
        self.cost = cost
    def bucket(self):
        return self.cost

items = Items(5)
print(items.bucket())
Chris Kenyon
  • 208
  • 1
  • 8