Reputation: 4675
I'm new to python and was working on this code:
class Shape:
def __init__(self, shape):
self.shape = shape
def shapeName(self):
print(self.shape)
class Rectangle(Shape): # Rectangle class inherits Shape
count = 0 # static variable
def __init__(self, name):
Shape.__init__(self.name)
print('In Rectangle')
Rectangle.count = Rectangle.count + 1
rec1 = Rectangle('Rectangle')
rec2 = Rectangle('Rectangle')
rec1.shapeName()
rec2.shapeName()
print( Rectangle.count )
I'm getting the following error:
C:\Python32\python.exe C:/Users/ashutosh/PycharmProjects/Test/InheritanceTest.py
Traceback (most recent call last):
File "C:/Users/ashutosh/PycharmProjects/Test/InheritanceTest.py", line 17, in <module>
rec = Rectangle('Rectangle')
File "C:/Users/ashutosh/PycharmProjects/Test/InheritanceTest.py", line 13, in __init__
Shape.__init__(name)
TypeError: __init__() takes exactly 2 arguments (1 given)
Process finished with exit code 1
The first argument to constructor is the current object and second is the name of the shape. Then why it is saying that I have to pass 2 arguments?
Upvotes: 1
Views: 162
Reputation: 19189
Shape
is a class, not an object, so when you call Shape.__init__
there's no self variable. In other words, there is no instance of Shape to call init on. The instance you want is the subclass instance of Shape
that you have, i.e. self
(the Rectangle
). You could simply pass self, like this:
Shape.__init__(self, name)
or make use of the super
keyword:
super(Rectangle, self).__init__(name)
The super
keyword allows you to implicitly refer to your superclass, without using the name.
In Python 3.0 you can simply write super().__init__(name)
without even the child reference.
Upvotes: 4
Reputation: 5627
You have to pass self
explicitly to Shape.__init__
.
So your rectangle class should look like this:
class Rectangle(Shape): # Rectangle class inherits Shape
count = 0
def __init__(self, name):
Shape.__init__(self, name)
print('In Rectangle')
Upvotes: 4