用简易代码快速学习Python(七)

本学习系列介绍:

本学习系列主要针对对编程略有了解有其他语言基础并要进一步学习Python的同学,通过简易的代码快速入门掌握Python语言。

系列总目录:
用简易代码快速学习Python(一)
用简易代码快速学习Python(二)
用简易代码快速学习Python(三)
用简易代码快速学习Python(四)
用简易代码快速学习Python(五)
用简易代码快速学习Python(六)
用简易代码快速学习Python(七)
用简易代码快速学习Python(八)
用简易代码快速学习Python(九)
用简易代码快速学习Python(十)

Day07:

继承:

class MyList(list):
    pass

list1 = MyList()
list1.append(5)
list1.append(1)
list1.append(9)
print(list1) #输出:[5, 1, 9]
list1.sort()
print(list1) #输出:[1, 5, 9]
class Animal:
    def __init__(self, name, age, hungry):
        self.__name = name
        self.age = age
        self.hungry = hungry

    def run(self):
        print("跑")

class Dog(Animal):
    def __init__(self, name, age, hungry, dogType):
        super().__init__(name, age, hungry)
        self.dogType = dogType

    def bark(self):
        print("叫")

d = Dog("旺财", 5, True, "金毛")
d.run() #输出:跑
d.bark() #输出:叫

Python可以多重继承,格式为“class 子类名(父类1, 父类2, ……)”,但是很容易出现未知bug,尽可能不用。

伪私有机制:

Python的类中属性的私有化,可以在名字前用“__”来实现,但其实这种私有化为伪私有,实际上Python只是将名字改为“_类名__变量名”来隐藏了起来。

例如:

class Person():
    __name = 'abc'
    def getName(self):
        return self.__name

p = Person()
print(p.__name) #报错
print(p.getName()) #输出:abc
print(p._Person__name) #输出:abc

所以,Python的类其实没有权限控制。

魔法方法:

魔法方法含义
基本的魔法方法
__new__(cls[, …])1. __new__ 是在一个对象实例化的时候所调用的第一个方法 2. 它的第一个参数是这个类,其他的参数是用来直接传递给 __init__ 方法 3. __new__ 决定是否要使用该 __init__ 方法,因为 __new__ 可以调用其他类的构造方法或者直接返回别的实例对象来作为本类的实例,如果 __new__ 没有返回实例对象,则 __init__ 不会被调用 4. __new__ 主要是用于继承一个不可变的类型比如一个 tuple 或者 string
__init__(self[, …])构造器,当一个实例被创建的时候调用的初始化方法
__del__(self)析构器,当一个实例被销毁的时候调用的方法
__call__(self[, args…])允许一个类的实例像函数一样被调用:x(a, b) 调用 x.__call__(a, b)
__len__(self)定义当被 len() 调用时的行为
__repr__(self)定义当被 repr() 调用时的行为
__str__(self)定义当被 str() 调用时的行为
__bytes__(self)定义当被 bytes() 调用时的行为
__hash__(self)定义当被 hash() 调用时的行为
__bool__(self)定义当被 bool() 调用时的行为,应该返回 True 或 False
__format__(self, format_spec)定义当被 format() 调用时的行为
有关属性
__getattr__(self, name)定义当用户试图获取一个不存在的属性时的行为
__getattribute__(self, name)定义当该类的属性被访问时的行为
__setattr__(self, name, value)定义当一个属性被设置时的行为
__delattr__(self, name)定义当一个属性被删除时的行为
__dir__(self)定义当 dir() 被调用时的行为
__get__(self, instance, owner)定义当描述符的值被取得时的行为
__set__(self, instance, value)定义当描述符的值被改变时的行为
__delete__(self, instance)定义当描述符的值被删除时的行为
比较操作符
__lt__(self, other)定义小于号的行为:x < y 调用 x.__lt__(y)
__le__(self, other)定义小于等于号的行为:x <= y 调用 x.__le__(y)
__eq__(self, other)定义等于号的行为:x == y 调用 x.__eq__(y)
__ne__(self, other)定义不等号的行为:x != y 调用 x.__ne__(y)
__gt__(self, other)定义大于号的行为:x > y 调用 x.__gt__(y)
__ge__(self, other)定义大于等于号的行为:x >= y 调用 x.__ge__(y)
算数运算符
__add__(self, other)定义加法的行为:+
__sub__(self, other)定义减法的行为:-
__mul__(self, other)定义乘法的行为:*
__truediv__(self, other)定义真除法的行为:/
__floordiv__(self, other)定义整数除法的行为://
__mod__(self, other)定义取模算法的行为:%
__divmod__(self, other)定义当被 divmod() 调用时的行为
__pow__(self, other[, modulo])定义当被 power() 调用或 ** 运算时的行为
__lshift__(self, other)定义按位左移位的行为:<<
__rshift__(self, other)定义按位右移位的行为:>>
__and__(self, other)定义按位与操作的行为:&
__xor__(self, other)定义按位异或操作的行为:^
__or__(self, other)定义按位或操作的行为:|
反运算
__radd__(self, other)(与上方相同,当左操作数不支持相应的操作时被调用)
__rsub__(self, other)(与上方相同,当左操作数不支持相应的操作时被调用)
__rmul__(self, other)(与上方相同,当左操作数不支持相应的操作时被调用)
__rtruediv__(self, other)(与上方相同,当左操作数不支持相应的操作时被调用)
__rfloordiv__(self, other)(与上方相同,当左操作数不支持相应的操作时被调用)
__rmod__(self, other)(与上方相同,当左操作数不支持相应的操作时被调用)
__rdivmod__(self, other)(与上方相同,当左操作数不支持相应的操作时被调用)
__rpow__(self, other)(与上方相同,当左操作数不支持相应的操作时被调用)
__rlshift__(self, other)(与上方相同,当左操作数不支持相应的操作时被调用)
__rrshift__(self, other)(与上方相同,当左操作数不支持相应的操作时被调用)
__rand__(self, other)(与上方相同,当左操作数不支持相应的操作时被调用)
__rxor__(self, other)(与上方相同,当左操作数不支持相应的操作时被调用)
__ror__(self, other)(与上方相同,当左操作数不支持相应的操作时被调用)
增量赋值运算
__iadd__(self, other)定义赋值加法的行为:+=
__isub__(self, other)定义赋值减法的行为:-=
__imul__(self, other)定义赋值乘法的行为:*=
__itruediv__(self, other)定义赋值真除法的行为:/=
__ifloordiv__(self, other)定义赋值整数除法的行为://=
__imod__(self, other)定义赋值取模算法的行为:%=
__ipow__(self, other[, modulo])定义赋值幂运算的行为:**=
__ilshift__(self, other)定义赋值按位左移位的行为:<<=
__irshift__(self, other)定义赋值按位右移位的行为:>>=
__iand__(self, other)定义赋值按位与操作的行为:&=
__ixor__(self, other)定义赋值按位异或操作的行为:^=
__ior__(self, other)定义赋值按位或操作的行为:|=
一元操作符
__pos__(self)定义正号的行为:+x
__neg__(self)定义负号的行为:-x
__abs__(self)定义当被 abs() 调用时的行为
__invert__(self)定义按位求反的行为:~x
类型转换
__complex__(self)定义当被 complex() 调用时的行为(需要返回恰当的值)
__int__(self)定义当被 int() 调用时的行为(需要返回恰当的值)
__float__(self)定义当被 float() 调用时的行为(需要返回恰当的值)
__round__(self[, n])定义当被 round() 调用时的行为(需要返回恰当的值)
__index__(self)1. 当对象是被应用在切片表达式中时,实现整形强制转换 2. 如果你定义了一个可能在切片时用到的定制的数值型,你应该定义 __index__ 3. 如果 __index__ 被定义,则 __int__ 也需要被定义,且返回相同的值
上下文管理(with 语句)
__enter__(self)1. 定义当使用 with 语句时的初始化行为 2. __enter__ 的返回值被 with 语句的目标或者 as 后的名字绑定
__exit__(self, exc_type, exc_value, traceback)1. 定义当一个代码块被执行或者终止后上下文管理器应该做什么 2. 一般被用来处理异常,清除工作或者做一些代码块执行完毕之后的日常工作
容器类型
__len__(self)定义当被 len() 调用时的行为(返回容器中元素的个数)
__getitem__(self, key)定义获取容器中指定元素的行为,相当于 self[key]
__setitem__(self, key, value)定义设置容器中指定元素的行为,相当于 self[key] = value
__delitem__(self, key)定义删除容器中指定元素的行为,相当于 del self[key]
__iter__(self)定义当迭代容器中的元素的行为
__reversed__(self)定义当被 reversed() 调用时的行为
__contains__(self, item)定义当使用成员测试运算符(in 或 not in)时的行为

例如:

class C():
    def __init__(self):
        print("调用__init__方法......")
    def __new__(cls):
        print("调用__new__方法......")
        return object.__new__(cls)
    def __del__(self):
        print("调用__del__方法......")

c1 = C()
#输出:
#调用__new__方法......
#调用__init__方法......
#调用__del__方法......
class Color:
    red = 'red'

    def __getattr__(self, item):
        # 在实例没有item属性的时候,调用该方法
        print("getattr is being called")
        return 'whatever'

    def __getattribute__(self, item):
        # 实例有没有item属性,都会调用该方法
        print("getattribute is being called")
        return super().__getattribute__(item)


color = Color()
print(color.red)
#输出:
#getattribute is being called
#red
print(color.blue)
#输出:
#getattribute is being called
#getattr is being called
#whatever

类、类对象、实例对象:

class C:
    count = 0

a = C()
b = C()
c = C()

c.count += 10
C.count += 100

print(a.count) #输出:100
print(b.count) #输出:100
print(c.count) #输出:10

注意:当执行c.count += 10时,才会真正的创建专属于实例对象c的实例属性count,此时a和b还都与类对象C的count相一致。

如果属性名和方法名相同,则属性会覆盖方法:

class C:
    def x(self):
        print(123)

c = C()
c.x = 1
print(c.x) #输出:1
print(c.x()) #报错

绑定:

绑定:Python严格要求方法需要有实例才能被调用,这种限制叫做绑定。

class CC():
    def setXY(self, x, y):
        self.x = x
        self.y = y
    def printXY(self):
        print(self.x, self.y)

dd = CC()
print(dd.__dict__) #输出:{}
print(CC.__dict__) 
#输出:{'__module__': '__main__', 'setXY': <function CC.setXY at 0x00000157A786C048>, 'printXY': <function CC.printXY at 0x00000157A786C9D8>, '__dict__': <attribute '__dict__' of 'CC' objects>, '__weakref__': <attribute '__weakref__' of 'CC' objects>, '__doc__': None}

CC.setXY(dd, 1, 2) #若写成CC.setXY(1, 2)会报错,提示缺少参数y。
CC.printXY(dd) #若写成CC.printXY()会报错,提示缺少参数self。输出:1 2
del CC
dd.setXY(4, 5)
dd.printXY() #输出:4 5

解释:类所加载的属性和方法属于静态变量,就算类被删除也会一直存放在内存中,直到程序退出时才会被释放。

所以,只有在特殊情况下才会使用类调用属性和方法,而此时由于绑定的原因,方法必须要有实例作为参数。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘学长丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值