深刻理解Python中的元类(metaclass)--代码实践

时间:2021-09-28 02:09:40

根据http://blog.jobbole.com/21351/所作的代码实践。

这篇讲得不错,但以我现在的水平,用到的机会是很少的啦。。。

#coding=utf-8

class ObjectCreator(object):
    pass

my_object = ObjectCreator()
# print my_object
def echo(o):
    print o

echo(ObjectCreator)
print hasattr(ObjectCreator, 'new_attribute')
ObjectCreator.new_attribute = 'foo'
print hasattr(ObjectCreator, 'new_attribute')
print ObjectCreator.new_attribute
ObjectCreatorMirror = ObjectCreator
print ObjectCreatorMirror()

def choose_class(name):
    if name == 'foo':
        class Foo(object):
            pass
        return Foo
    else:
        class Bar(object):
            pass
        return Bar

print '========================'
MyClass = choose_class('foo')
print MyClass
print MyClass()

print '============================'
print type(1)
")
print type(ObjectCreator)
print type(ObjectCreator())
print '=========================='
MyShinyClass = type('MyShinyClass', (), {})
print MyShinyClass
print MyShinyClass()
print '========================='
Foo = type('Foo', (), {'bar':True})
print Foo
print Foo.bar
f = Foo()
print f
print f.bar
print '======================'
FooChild = type('FooChild', (Foo,), {})
print FooChild
print FooChild.bar
print '==========================='
def echo_bar(self):
    print self.bar

FooChild = type('FooChild', (Foo,),{'echo_bar': echo_bar})
print hasattr(Foo, 'echo_bar')
print hasattr(FooChild, 'echo_bar')
my_foo = FooChild()
print my_foo.echo_bar()
print '============================='
age = 35
print age.__class__
name = 'bob'
print name.__class__
def foo():  pass
print foo.__class__
class Bar(object):  pass
b = Bar()
print b.__class__
print '============================'
print age.__class__.__class__
print name.__class__.__class__
print foo.__class__.__class__
print b.__class__.__class__
print '============================'

class UpperAttrMetaClass(type):
    def __new__(cls, name, bases, dct):
        attrs = ((name, value) for name, value in dct.items() if not name.startswith('__'))
        uppercase_attr = dict((name.upper(), value) for name, value in attrs)
        return super(UpperAttrMetaClass, cls).__new__(cls, name, bases, uppercase_attr)

class Foo(object):
    __metaclass__ = UpperAttrMetaClass
    bar = 'bip'

print hasattr(Foo, 'bar')
print hasattr(Foo, 'BAR')
f = Foo()
print f.BAR

print '============================'

深刻理解Python中的元类(metaclass)--代码实践