继承

一、继承

继承(所有属性和方法)

class 类名(父类):
      pass

class Cls:
    pass

class Cls1(Cls):
    pass

多继承

class 类名(父类1,父类2,父类3....父类N):
     pass

class Father:
    height = 180
class Mother:
    height = 175
class Child(Mother, Father):
    pass
print(Child.height) #会优先继承第一顺位父类的所有属性和方法

继承顺序的查看

类名.mro()

super

class Base:
    height = 168
    def att(self):
        print("111")

class Father(Base):
    height = 180
    def att(self):
        print("123")
class Mother(Base):
    height = 175
    def att(self):
        print("456")

class Child(Father, Mother):
    def att(self):
        super().att()
        print(super(Father, self).height)
# print(Child.mro())
c = Child()
c.att()
print(Father.height)

二、魔术方法

_str_:方法可以被多种方式触发,适用于给用户提供必要信息,便于用户使用产品

 _repr_:可以被特定方法触发,受用于开发者提供必要信息,便于测试以及维护

class Cls:

    def __repr__(self):  #打印实例时触发
        print("触发repr方法")
        #给开发者 1.更详细的错误信息
        #        2.请求的地址, 参数, 哪一步
        return "repr返回值"

    def __str__(self):  #repr和str同时存在 触发str
        print("触发str方法")
        #一般时给用户看
        return "str返回值"

c = Cls()
# print(c) #默认有自己的 这种魔术方法
# print(str(c)) #打印str触发repr方法
# ret_str = str(c)
# print(ret_str)
ret_repr = repr(c)
print(ret_repr)

_call_:执行实例名()将会触发_call_

class Cls:

    def __call__(self, *args, **kwargs):
        print("触发call")

# c = Cls() #实例
# c()
Cls()()

_class_:查看类名

_dict_:查看全部属性,返回属性和属性值键值对形式

_doc_:查看对象文档,即类中的注释(用引号注释的部分)

_dir_:查看全部属性和方法

posted @ 2018-08-12 15:44  lk_hacker  阅读(86)  评论(0编辑  收藏  举报