Python入门基础(下)之魔方方法

Python入门基础(下)之魔方方法

一.学习内容概括

学习地址:https://tianchi.aliyun.com/s/58327c15d1faee512c008128d3bb9e32

今天主要学习的内容有:魔方方法

二.具体学习内容

魔法方法

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

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

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

魔法方法的第一个参数应为cls(类方法) 或者self(实例方法)。

  • cls:代表一个类的名称
  • self:代表一个实例对象的名称

基本的魔法方法

  • __init__(self[, ...]) 构造器,当一个实例被创建的时候调用的初始化方法

【例子】

class Rectangle:

    def __init__(self, x, y):
        self.x = x
        self.y = y
​
    def getPeri(self):
        return (self.x + self.y) * 2
​
    def getArea(self):
        return self.x * self.y
​
​
rect = Rectangle(4, 5)
print(rect.getPeri())  # 18
print(rect.getArea())  # 20
18
20
  • __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 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__(A, *args, **kwargs)  # 改动了cls变为A
​
​
b = B(10)
​
# 结果:
# into B __new__
# <class '__main__.B'>
# into A __new__
# <class '__main__.A'>
into B __new__
<class '__main__.B'>
into A __new__
<class '__main__.B'>
into B __init__
into B __new__
<class '__main__.B'>
into A __new__
<class '__main__.A'>
  • __new__没有正确返回当前类cls的实例,那__init__是不会被调用的,即使是父类的实例也不行,将没有__init__被调用。

【例子】利用__new__实现单例模式。

class Earth:

    pass
​
​
a = Earth()
print(id(a))  # 260728291456
b = Earth()
print(id(b))  # 260728291624
​
class Earth:
    __instance = None  # 定义一个类属性做判断
​
    def __new__(cls):
        if cls.__instance is None:
            cls.__instance = object.__new__(cls)
            return cls.__instance
        else:
            return cls.__instance
​
​
a = Earth()
print(id(a))  # 512320401648
b = Earth()
print(id(b))  # 512320401648
2336598724336
2336598528464
2336598467752
2336598467752
  • __new__方法主要是当你继承一些不可变的 class 时(比如int, str, tuple), 提供给你一个自定义这些类的实例化过程的途径。

【例子】

class CapStr(str):

    def __new__(cls, string):
        string = string.upper()
        return str.__new__(cls, string)
​
​
a = CapStr("i love lsgogroup")
print(a)  # I LOVE LSGOGROUP
I LOVE LSGOGROUP
  • __del__(self) 析构器,当一个对象将要被系统回收之时调用的方法。

Python 采用自动引用计数(ARC)方式来回收对象所占用的空间,当程序中有一个变量引用该 Python

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值