zoukankan      html  css  js  c++  java
  • Python----面向对象---练习一:在元类中控制把自定义类的数据属性都变成大写

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

     1 class Mymeta(type):
     2     def __new__(cls, class_name, class_bases, class_dic):
     3         print(cls)
     4         print(class_name)
     5         print(class_bases)
     6         print(class_dic)
     7         update_attrs = {}
     8         for k, v in class_dic.items():
     9             if not callable(v) and not k.startswith('__'):
    10                 update_attrs[k.upper()] = v
    11             else:
    12                 update_attrs[k] = v
    13         print(update_attrs)
    14         return type.__new__(cls, class_name, class_bases, update_attrs)
    15 
    16 
    17 class Chinese(object, metaclass=Mymeta):
    18     '''
    19     xxx
    20     '''
    21 
    22     country = 'China'
    23     tag = '123'
    24 
    25     def __init__(self, name, age):
    26         self.name = name
    27         self.age = age
    28 
    29     def talk(self):
    30         print('%s is talking' % self.name)
    31 
    32 print(Chinese.__dict__)
    33 
    34 结果为:
    35 
    36 <class '__main__.Mymeta'>
    37 Chinese
    38 (<class 'object'>,)
    39 {'__module__': '__main__', '__qualname__': 'Chinese', '__doc__': '
        xxx
        ', 'country': 'China', 'tag': '123', '__init__': <function Chinese.__init__ at 0x00000236B593B620>, 'talk': <function Chinese.talk at 0x00000236B593B6A8>}
    40 {'__module__': '__main__', '__qualname__': 'Chinese', '__doc__': '
        xxx
        ', 'COUNTRY': 'China', 'TAG': '123', '__init__': <function Chinese.__init__ at 0x00000236B593B620>, 'talk': <function Chinese.talk at 0x00000236B593B6A8>}
    41 {'__module__': '__main__', '__doc__': '
        xxx
        ', 'COUNTRY': 'China', 'TAG': '123', '__init__': <function Chinese.__init__ at 0x00000236B593B620>, 'talk': <function Chinese.talk at 0x00000236B593B6A8>, '__dict__': <attribute '__dict__' of 'Chinese' objects>, '__weakref__': <attribute '__weakref__' of 'Chinese' objects>}

    找到数据属性,然后对数据属性进行操作,

  • 相关阅读:
    Python环境变量设置
    Java基础视频笔记(八):多线程编程
    Java基础视频笔记(六):本地文件操作
    设计延迟加载的“单例设计模式”
    Java数组去除重复元素
    博客园真不错,终于发现一个清净之处
    [Architecture Design] 系统边界设计
    [Chatter] 架构设计是做甚么
    [DCF] Devices Communication Foundation Architecture V4
    [WPF] DataTemplate Binding to Interface
  • 原文地址:https://www.cnblogs.com/xudachen/p/8667034.html
Copyright © 2011-2022 走看看