page contents

通过元类实现单例模式

通过元类实现单例模式

class A:

    b = 2

    def test(self):

        print('这是test')


# hasattr()函数用于判断对象是否包含对应的属性或方法。

# 参数是一个对象和一个字符串,如果字符串是对象的属性值,函数返回True,反之返回False.

# 判断是否包含属性b

print(hasattr(A(), 'b')) #True

# 判断是否包含test方法

print(hasattr(A(), 'test'))  #True

 

------------------------------------------------------------    

class A:

    def __init__(self, name):

        self.name = name


    def __new__(cls, *args, **kwargs):  # self 实例本身   cls 类本身

        if not hasattr(cls, 'ins'):   # hasattr(cls, 'ins')cls没有ins属性时为False,加not则为True; 即cls没有ins这个属性时,执行下面的语句

            cls.ins = super().__new__(cls)

        return cls.ins


a = A('张三')   # 名字不一样 但是人一样

b = A('李四')

print(id(a))   # id都是一样的 只不过换了个名字而已

print(id(b))

print(a.name)

print(b.name)  #  都是李四   他会覆盖 之前的参数

运行结果:

1803858843744

1803858843744

李四

李四

  • 发表于 2021-10-12 14:59
  • 阅读 ( 493 )
  • 分类:Python开发

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
Wilia
Wilia

28 篇文章

作家榜 »

  1. 轩辕小不懂 2403 文章
  2. 小柒 1324 文章
  3. Pack 1135 文章
  4. Nen 576 文章
  5. 王昭君 209 文章
  6. 文双 71 文章
  7. 小威 64 文章
  8. Cara 36 文章