class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * self.length + 2 * self.width
class Square:
def __init__(self, length):
self.length = length
def area(self):
return self.length * self.length
def perimeter(self):
return 4 * self.length
a = Rectangle(4, 6)
print("a.area() =", a.area())
print("a.perimeter() =", a.perimeter(), "\n")
b = Square(7)
print("b.area() =", b.area())
print("b.perimeter() =", b.perimeter())
a.area() = 24
a.perimeter() = 20
b.area() = 49
b.perimeter() = 28
상속을 사용하면 (1) 코드 줄이면서, (2) 관계를 규정
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * self.length + 2 * self.width
# Here we declare that the Square class inherits from the Rectangle class
class Square(Rectangle):
def __init__(self, length):
super().__init__(length, length)
The benefits of super() in single-inheritance are minimal -- mostly, you don't have to hard-code the name of the base class into every method that uses its parent methods.
However, it's almost impossible to use multiple-inheritance without super(). This includes common idioms like mixins, interfaces, abstract classes, etc. This extends to code that later extends yours. If somebody later wanted to write a class that extended Child and a mixin, their code would not work properly.
Definition. Mixins are a language concept that allows a programmer to inject some code into a class. Mixin programming is a style of software development, in which units of functionality are created in a class and then mixed in with other classes.
What's the difference?
SomeBaseClass.__init__(self)
means to call SomeBaseClass's __init__. while
super(Child, self).__init__()
means to call a bound __init__ from the parent class that follows Child in the instance's Method Resolution Order (MRO).
If the instance is a subclass of Child, there may be a different parent that comes next in the MRO.
Python 2 versus 3
This works in Python 2 and 3:
super(Child, self).__init__()
This only works in Python 3:
super().__init__()
댓글
댓글 쓰기