码迷,mamicode.com
首页 > 编程语言 > 详细

python2与python3中__metacalss__的不同用法

时间:2018-09-12 17:05:53      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:tac   star   不同   ict   pytho   key   function   int   blog   

python3

def upper_attr(future_class_name, future_class_parents, future_class_attr):
    attrs = ((name, value) for name, value in future_class_attr.items() if not name.startswith(‘__‘))
    uppercase_attr = dict((name.upper(), value) for name, value in attrs)
    return type(future_class_name, future_class_parents, uppercase_attr)

class Foo(metaclass = upper_attr):
    bar = ‘bip‘

print(hasattr(Foo, ‘bar‘))
print(hasattr(Foo, ‘BAR‘))
f = Foo()
print(hasattr(f,‘bar‘))
print(hasattr(f,‘BAR‘))
输出:

False
True
False
True

Process finished with exit code 0

 

 

python2:

def upper_attr(futer_class_name, future_class_parent, futuer_class_attr):

   attrs = ((name, value) for name, value in futuer_class_attr.item() if name.startswith(‘__‘))

  uppercase_attr = dict((name.upper(),value) for name, value in attrs)

  return type(futer_class_name, future_class_parent, uppercase_attr)

__metaclass__ = upper_attr

class Foo(object):

  bar = ‘bip‘

print(hasattr(Foo, ‘bar‘))

print(hasattr(Foo, ‘BAR‘))

f = Foo()

print(hasattr(f,‘bar‘))

print(hasattr(f,‘BAR‘))

 

关于Python2对__metaclass__的跟详细的解释请看:

http://blog.jobbole.com/21351/               -------------python2中__metaclass__的用法

 

python2与python3中__metacalss__的不同用法

标签:tac   star   不同   ict   pytho   key   function   int   blog   

原文地址:https://www.cnblogs.com/qingsheng/p/9635313.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!