Python - 单继承(__str__+__repr__)

版权声明:转载请注明出处 https://blog.csdn.net/qq_42292831/article/details/90701636

# MRO: method resolution order 方法解析顺序
# solute 溶质
# solution 溶液、解决方案
# resolute 坚决的、果断的
# resolution 解决、解析
# string 字符串
# represent 代表、表示
# reproduce 复制、再生



Example

#可以省略括号,也可以加上括号,也可以在括号中加入Object
class Shape(object):
    def __init__(self,color='red'):
        self.__color=color;
        self._test_data = 'Test_data'
    def __str__(self):
        return '>>>颜色:'+str(self.__color)
    def getArea(self):
        pass
    __repr__ = __str__
    
class Circle(Shape):
    def __init__(self,radius=0,color='red'):
        super().__init__(color)
        self.radius = radius
    def setRadius(self,radius):
        self.radius = radius;
    def getRadius(self):
        return self.radius
    def getArea(self):
        return 3.14*self.radius**2
    def __str__(self):
        return ">>>通过__str__输出:\n>>>Radius="+str(self.radius)+'\n'+">>>Area="+str(3.14*self.radius**2)
    __repr__ = __str__
    #可以使用super()方法来调用父类的方法
    def getColor(self):
        print(super().__str__())
    
        

if __name__ == "__main__":
    circle_1 = Circle(12,'black')
    print(circle_1)
    print(circle_1.getRadius())
    circle_1.setRadius(10)
    print(circle_1.getRadius())
    circle_1.getColor()
    
    print(Circle.__mro__)
    print(Circle.mro())


猜你喜欢

转载自blog.csdn.net/qq_42292831/article/details/90701636