第14讲 模块

__new __方法

class A(object):

    def __init__(self):
        print('__init__')

    def __new__(cls, *args, **kwargs):
        print('__new__')       #new方法被重写,不再执行父类的创建新实例的方法,所以其他的不再执行


a = A()

class A(object):

    def __init__(self):
        print('__init__')

    def __new__(cls,  *args, **kwargs):
        print('__new__')
        return super().__new__(cls)      #调用父类的new方法


a = A()

运行结果:
在这里插入图片描述

单例模式

#单例模式
class B():
    attribute = None    #类属性
    def __new__(cls, *args, **kwargs):
        if cls.attribute is None:       #先判断雷属性是否为None
            cls.attribute = super().__new__(cls)    #创建实例
            return cls.attribute     #返回实例
        else:
            return cls.attribute    #如果不为None,直接返回已存在的实例


b1 = B()
b2 = B()
print(id(b1), b1.attribute)
print(id(b2), b2.attribute)

运行结果:
在这里插入图片描述

模块

#test1 做为源模块
def a():

    return '函数'


a()


class B():

    def __init__(self,name):
        self.name = name


Alex = B('alex')

if __name__ == '__main__':   #这个if之后的代码,只在本模块中运行
    print(Alex.name)



c = 12
d = 13
import test1 as t   #引入test1,命名为t
print(t.a())


from test1 import *    #引入所有
from test1 import B    #从test1中引入B的类
bag = B('bag')
print(bag.name)

print(t.c + t.d)

运行结果:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值