[Python3]元类拓展

自定义元类控制类的创建

class Mymeta(type):
    def __init__(self, class_name, class_bases, class_dic):
        if not class_name.istitle():
            raise TypeError('类名首字母必须大写')

        if '__doc__' not in class_dic or not class_dic['__doc__'].strip():
            raise TypeError('必须有注释且注释必须不能为空')
        super().__init__(class_name, class_bases, class_dic)

class Chinese(object, metaclass=Mymeta):
    '''
    xxx
    '''
    country = 'China'
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def talk(self):
        print('%s is talking' % self.name)
# Chinese = Mymeta(class_name, class_bases, class_dic)


自定义元类控制类的实例化行为

# 知识储备:__call__方法
class Foo:
    def __call__(self, *args, **kwargs):
        print(self)
        print(args)
        print(kwargs)
obj = Foo()
obj(1,2,3,a=1,b=2,c=3) # obj.__call__(obj,1,2,3,a=1,b=2,c=3)
# 元类内部也应该有一个__call__方法,会在调用Foo时触发执行
# Foo(1,2,x=1)  # Foo.__call__(1,2,x=1)


自定义元类控制类的实例化行为的应用

实现方式一:
# 单例模式

class MySQL:
    __instance = None
    def __init__(self):
        self.host = '127.0.0.1'
        self.port = 3306
    @classmethod
    def singleton(cls):
        if not cls.__instance:
            obj = cls()
            cls.__instance = obj
        return cls.__instance

obj1 = MySQL.singleton()
obj2 = MySQL.singleton()
obj3 = MySQL.singleton()
print(obj1)
print(obj2)
print(obj3)
# <__main__.MySQL object at 0x1045a13c8>
# <__main__.MySQL object at 0x1045a13c8>
# <__main__.MySQL object at 0x1045a13c8>

实现方式二:
# 元类的方式

class Mymeta(type):
    def __init__(self, class_name, class_bases, class_dic):
        if not class_name.istitle():
            raise TypeError('类名首字母必须大写')
        if '__doc__' not in class_dic or not class_dic['__doc__'].strip():
            raise TypeError('必须有注释且注释必须不能为空')
        super().__init__(class_name, class_bases, class_dic)
        self.__instance = None

    def __call__(self, *args, **kwargs):
        if not self.__instance:
            obj = object.__new__(self)
            self.__init__(obj)
            self.__instance = obj
        return self.__instance

class Mysql(object,metaclass=Mymeta):
    '''
    xxxx
    '''
    def __init__(self):
        self.host = '127.0.0.1'
        self.port = 3306

obj1 = Mysql()
obj2 = Mysql()
obj3 = Mysql()
print(obj1 is obj2 is obj3)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值