python2与python3中__metacalss__的不同用法

Posted 思辨

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python2与python3中__metacalss__的不同用法相关的知识,希望对你有一定的参考价值。

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__的不同用法的主要内容,如果未能解决你的问题,请参考以下文章

Python2与Python3兼容

CSIC_716_20191102

02_pip区别: linux环境下python2,python3的

nose在python2与python3中的包的自动发现用例的区别

python2和python3中dict的__repr__()

Python2和Python3两者区别