Python入门系列(九、Python 的魔法方法)

魔法方法

据说,Python 的对象天生拥有一些神奇的方法,它们是面向对象的 Python 的一切…

它们是可以给你的类增加魔力的特殊方法…

如果你的对象实现了这些方法中的某一个,那么这个方法就会在特殊的情况下被 Python 所调用,而这一切都是自动发生的…

类有一个名为__init__(self[, param1, param2…])的魔法方法,该方法在类实例化时会自动调用。

class Computer:
    def __init__(self,name):
        self.name=name
    def output(self):
        print("电脑型号是"+self.name)
A=Computer("联想")
B=Computer("华为")
A.output()
B.output()

公有和私有

在 Python 中定义私有变量只需要在变量名或函数名前加上“__”两个下划线,那么这个函数或变量就会为私有的了。

class JustCounter:
    __secretCount = 0  # 私有变量
    publicCount = 0  # 公开变量

    def count(self):
        self.__secretCount += 1
        self.publicCount += 1
        print(self.__secretCount)


counter = JustCounter()
counter.count()  # 1
counter.count()  # 2
print(counter.publicCount)  # 2

# Python的私有为伪私有
print(counter._JustCounter__secretCount)  # 2 
print(counter.__secretCount) #会报错 
# AttributeError: 'JustCounter' object has no attribute '__secretCount'

继承

Python 同样支持类的继承,派生类的定义如下所示:

class DerivedClassName(BaseClassName):
       statement-1
              .
              .
              .
       statement-N

BaseClassName(基类名)必须与派生类定义在一个作用域内。除了类,还可以用表达式,基类定义在另一个模块中时这一点非常有用:

class DerivedClassName(modname.BaseClassName):
       statement-1
              .
              .
              .
       statement-N

Python 虽然支持多继承的形式,但我们一般不使用多继承,因为容易引起混乱。

class DerivedClassName(Base1, Base2, Base3):
       statement-1
              .
              .
              .
       statement-N

需要注意圆括号中父类的顺序,若是父类中有相同的方法名,而在子类使用时未指定,Python 从左至右搜索,即方法在子类中未找到时,从左到右查找父类中是否包含方法。方法名同,默认调用的是在括号中排前地父类的方法

组合

class Turtle:
    def __init__(self,x):
        self.x=x

class Fish:
    def __init__(self,x):
        self.x=x
        
class Pool:
    def __init__(self,x,y):
        self.turple=Turtle(x)
        self.fish=Fish(y)
    def print_result(self):
        print("游泳池里有%d只乌龟%d条鱼"%(self.turple.x,self.fish.x))
p=Pool(3,5)
p.print_result()

类、类对象和实例对象

在这里插入图片描述

什么是绑定?

Python 严格要求方法需要有实例才能被调用,这种限制其实就是 Python 所谓的绑定概念。

Python 对象的数据属性通常存储在名为.__ dict__的字典中,我们可以直接访问__dict__,或利用 Python 的内置函数vars()获取.__ dict__。
一些相关的内置函数(BIF)
issubclass(class, classinfo) 方法用于判断参数 class 是否是类型参数 classinfo 的子类。
一个类被认为是其自身的子类。
classinfo可以是类对象的元组,只要class是其中任何一个候选类的子类,则返回True。

魔法方法

魔法方法总是被双下划线包围,例如__init__。

魔法方法是面向对象的 Python 的一切,如果你不知道魔法方法,说明你还没能意识到面向对象的 Python 的强大。

魔法方法的“魔力”体现在它们总能够在适当的时候被自动调用。

魔法方法的第一个参数应为cls(类方法) 或者self(实例方法)。
cls:代表一个类的名称
self:代表一个实例对象的名称

new(cls[, …]) 在一个对象实例化的时候所调用的第一个方法,在调用__init__初始化前,先调用__new__。
new__至少要有一个参数cls,代表要实例化的类,此参数在实例化时由 Python 解释器自动提供,后面的参数直接传递给__init__。
new__对当前类进行了实例化,并将实例返回,传给__init__的self。但是,执行了__new,并不一定会进入__init__,只有__new__返回了,当前类cls的实例,当前类的__init__才会进入。

class A(object):
    def __init__(self, value):
        print("into A __init__")
        self.value = value

    def __new__(cls, *args, **kwargs):
        print("into A __new__")
        print(cls)
        return object.__new__(cls)


class B(A):
    def __init__(self, value):
        print("into B __init__")
        self.value = value

    def __new__(cls, *args, **kwargs):
        print("into B __new__")
        print(cls)
        return super().__new__(cls, *args, **kwargs)
b = B(10)
#into B __new__
#<class '__main__.B'>
#into A __new__
#<class '__main__.B'>
#into B __init__

算术运算符

类型工厂函数,指的是“不通过类而是通过函数来创建对象”。
在这里插入图片描述

class MyClass:

    def __init__(self, height, weight):
        self.height = height
        self.weight = weight

    # 两个对象的长相加,宽不变.返回一个新的类
    def __add__(self, others):
        return MyClass(self.height + others.height, self.weight + others.weight)

    # 两个对象的宽相减,长不变.返回一个新的类
    def __sub__(self, others):
        return MyClass(self.height - others.height, self.weight - others.weight)

    # 说一下自己的参数
    def intro(self):
        print("高为", self.height, " 重为", self.weight)


def main():
    a = MyClass(height=10, weight=5)
    a.intro()

    b = MyClass(height=20, weight=10)
    b.intro()

    c = b - a
    c.intro()

    d = a + b
    d.intro()


if __name__ == '__main__':
    main()

# 高为 10  重为 5
# 高为 20  重为 10
# 高为 10  重为 5
# 高为 30  重为 15

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值