元类练习题

练习一:在元类中控制把自定义类的数据属性都变成大写

复制代码
class Mymetaclass(type):
    def __new__(cls, name, bases, attrs):
        update_attrs={}
        for k,v in attrs.items():
            if not callable(v) and not k.startswith('__'):
                update_attrs[k.upper()] = v
            else:
                update_attrs[k]=v
        return type.__new__(cls, name, bases, update_attrs)

class Chinese(metaclass=Mymetaclass):
    country = 'China'
    tag = 'Legend of the Dragon'
    def walk(self):
        print('%s is walking' %self.name)

print(Chinese.__dict__)
"""
{'__module__': '__main__',
 'COUNTRY': 'China', 
 'TAG': 'Legend of the Dragon',
 'walk': <function Chinese.walk at 0x1040211e0>,
 '__dict__': <attribute '__dict__' of 'Chinese' objects>, 
 '__weakref__': <attribute '__weakref__' of 'Chinese' objects>, 
 '__doc__': None}
"""
复制代码

 

练习二:在元类中控制自定义的类无需init方法

1.元类帮其完成创建对象,以及初始化操作;

2.要求实例化时传参必须为关键字形式,否则抛出异常TypeError: must use keyword argument

3.key作为用户自定义类产生对象的属性,且所有属性变成大写

复制代码
class Mymetaclass(type):

    def __call__(self, *args, **kwargs):
        if args:
            raise TypeError('must use keyword argument for key function')
        obj = object.__new__(self)  # 创建对象,self为类Foo

        for k,v in kwargs.items():
            obj.__dict__[k.upper()] = v
        return obj


class Chinese(metaclass=Mymetaclass):
    country = 'China'            # 需要大写的数据属性
    tag = 'Legend of the Dragon'
    def walk(self):
        print('%s is walking' %self.name)

p=Chinese(name='Jack', age=18, sex='male')
print(Chinese.__dict__)
"""
{'__module__': '__main__', 
'country': 'China', 
'tag': 'Legend of the Dragon', 
'walk': <function Chinese.walk at 0x1040211e0>, 
'__dict__': <attribute '__dict__' of 'Chinese' objects>, 
'__weakref__': <attribute '__weakref__' of 'Chinese' objects>, 
'__doc__': None}
"""
复制代码

 

posted @   休耕  阅读(316)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示