python基础知识09-继承,多继承和魔术方法

1.继承

class Father:

def init(self,age,sex):

self.age = age

self.sex = sex

class Son(Father): 类名后面写括号,括号中放父类名.

pass

class Dog(默认继承object类):所有类的父类

pass

不可以访问父类私有属性.双下划线属性.除非在内部定义一个super().__私有属性,的方法访问.

class Son(Father):

def bb(self):

print(Father.__a) #私有属性不能访问.

调用的时候先在自己的类中找,然后在父类中找. 类 直接基类 间接基类 最终是object类

bases:查看类的直接父类,特殊属性,返回tuple

类在生成时会自动生成方法解析顺序可以通过 类名.mro()来查看.mro;

前面加两个下划线是私有属性,两边加不是.

super().aa(),调用直接父类的方法

son.mor()方法,查看父属性

 

2.多继承

class Father:

def aa():

print()

class Mother:

def aa():

print()

class Son(Father,Mother):

pass

a = Son()

a.aa() 如果多继承都有aa方法.先去继承前面的,就是从左往右.

通过重写覆盖掉父类的方法.

def aa(self):

print('这是我的')

重写后又想用父类的方法:

1.Father.aa(Father(1,2)) 类名调用必须要用实例,或者传self;

2.super().aa() 直接调用父类的方法,但是无法访问双下划线的私有属性.

class Base:

def play(self):

super().play()

print('这是Base')

class A(Base):

def play(self):

super().play()

print('这是A')

class B(Base):

def play(self):

super().play()

print('这是B')

class C(A,C):

def play(self):

super().play()

print('这是C)

3.魔术方法.

class Aa:

def init(self.num):

self.num = num

def add(self, other):

s = self.num + other.num

return s

a = Aa(5)

b = Aa(9)

print(a + b)

add(self,other)魔术方法

sub() #x-y

mul() # x *y

mod() # x%y

iadd() # x+=y

isub() # x-=y

radd() # y+x

rsub() # y-x

imul() # x *= y

imod() # x %=y

str和repr原理:在python中,str和repr方法在处理对象的时候,分别调用的是对象的str()和repr()方法,print打印对象,调用str函数,如果对象没有定义str方法,则调用repr()方法处理,在交互模式下,直接输出对象,显示repr()的返回值.

如果在类里找不到str()方法,就会执行repr()方法,如果类中没有repr方法,就去父类里面找.

str方法 和repr方法要写返回值,return,不写会报错.

对使用者友好的str()

对开发者调试友好的repr()

call方法,魔术方法 调用时触发,可以使类的实例进行调用.

pycharm中如何设置交互模式,run > edit configration > 勾选第三个选项.

类中查询相关信息的方法(了解即可)

class 查看类名 实例.--class--

dict 查看全部属性,返回属性和属性值键值对形式 实例.--dict--

--doc-- 查看对象文档,即类中用三个引号引起来的部分. 类名.--dict--

--bases-- 查看父类 类名.--base--

--mro-- 查看多继承的情况下,子类调用父类方法时,搜索顺序. 子类名.--mro--

实例.--class--.--mro--

4.基于多继承的Mix-in设计模式

传统分类思想 转变 为 拼积木思想.

分类思想: 动物 > 人>> 男人,女人

Mix-in思想:胳膊,脑袋,腿>> 人

注意:一般,"Mix-in类"是继承的终点!

 

 

猜你喜欢

转载自www.cnblogs.com/winfun/p/10983826.html
今日推荐