hausaufgabe--python 38 -- extends of Class

00-- requirements 

a. to define a class of Point and a class of Line with Point as parent

b. define a function in Line to calculate the lenth of 2 points. 

import math

class Point:
    def __init__(self,x,y):
        self.x = x
        self.y = y

        return (self.x, self.y)

class Line(Point):
    def __init__(self,x1,y1,x2,y2):
        self.point1 = Point.__init__(self,x1,y1)
        self.point2 = Point.__init__(self,x2,y2)
    


    def getLen(self):
        return math.hypot((self.point1[0]-self.point2[0]),(self.point1[1]-self.point2[1]))

PS:

with extend, there are 2 ways to redefine the functions in parent class, e.g. the __init__(self) function in Point

with extent, Line can reuse the __init__(self) in Point as below:

1-- 

Point.__init__(self)

2--

super().__init__()

Be careful, when you use the second way with super(), don't add "self" as prameter anymore. 

class Line(Point):
    def __init__(self,x1,y1,x2,y2):
        self.point1 = super().__init__(x1,y1)
        self.point2 = super().__init__(x2,y2)

If I add with self, when running, the error will be shown as below:

>>> l = Line(1,2,3,4)
Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    l = Line(1,2,3,4)
  File "C:/其他应用/python/Lib/idlelib/extendtest.py", line 12, in __init__
    self.point1 = super().__init__(self,x1,y1)
TypeError: __init__() takes 3 positional arguments but 4 were given

001-- __init__(self) function in class

__init__(self) function is used to define the attributes of the class, it won't return other things except None. 

e.g. 

class MyClass:
   def __init__(self):
      return "I love python.com!"

with running, it will show :

>>> myClass = MyClass()
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
myClass = MyClass()
TypeError: __init__() should return None, not 'str'

002-- multiple extends 

It might caused some unknow serious issues. 

class A():
    def __init__(self):
        print("进入A…")
        print("离开A…")

class B(A):
    def __init__(self):
        print("进入B…")
        A.__init__(self)
        print("离开B…")
        
class C(A):
    def __init__(self):
        print("进入C…")
        A.__init__(self)
        print("离开C…")

class D(B, C):
    def __init__(self):
        print("进入D…")
        B.__init__(self)
        C.__init__(self)
        print("离开D…")

Running result:

>>> d = D()
进入D…
进入B…
进入A…
离开A…
离开B…
进入C…
进入A…
离开A…
离开C…
离开D…

As you can see, class A have been init 2 times. 

To avoid this, please use super() for the init, or avoid multiple extends cases. 

referred:

http://bbs.fishc.com/thread-48759-1-1.html

原文地址:https://www.cnblogs.com/Shareishappy/p/7491818.html