Reputation: 1
I'm not sure why this is happening. It seems to think that "self" requires an argument, which doesn't make any sense.
Here's my code:
class Animal:
def __init__(self):
self.quality = 1
class Bear(Animal):
def __init__(self):
Animal.__init__(self)
def getImage(self):
return "bear.ppm"
class Fish(Animal):
def __init__(self):
Animal.__init__(self)
def getImage(self):
return "fish.ppm"
And the error I get is:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
Bear.getImage()
TypeError: getImage() takes exactly 1 argument (0 given)
Upvotes: 0
Views: 72
Reputation: 4759
getImage() is an instance method, so it can only be called with a instantiation of Bear class. So here is how you can do it:
Bear().getImage()
or
be = Bear()
be.getImage()
Upvotes: 0
Reputation: 94871
You have to instantiate Bear
before you call getImage()
:
b = Bear()
b.getImage()
getImage
is an instance method, so it is only designed to be called on a specific instance of the Bear
class. The state of that instance is what is passed as the self
variable to getImage
. Calling b.getImage()
is equivalent to this:
b = Bear()
Bear.getImage(b)
So, without an instance of Bear
, there is nothing that can be used for the self
argument, which is why you see that exception when you called Bear.getImage()
. See the documentation on Python instance methods for more information.
If you want to be able to call getImage
on the class Bear
rather than on a specific instance, you need to make it a static method, using the @staticmethod
decorator:
class Bear(Animal):
def __init__(self):
Animal.__init__(self)
@staticmethod
def getImage():
return "bear.ppm"
Then you could call Bear.getImage()
.
Upvotes: 8