[TimLinux] Python 元类

1. type函数

name = "This is a string"
print(type(name))  # <class 'str'>
print("*" * 10, "分界线", "*" * 10)

cls = type('Foo', (), {})
f = cls()
print(type(f))  # <class '__main__.Foo'>
print(type(cls))  # <class 'type'>
print(cls.__name__)  # Foo
print("*" * 10, "分界线", "*" * 10)

def init(self, name, age):
    self.name = name
    self.age = age
    print(self.name, self.age)

cls = type('Foo', (object, ), {'__init__': init})
f = cls('Tim', 22)  # Tim 22
View Code

2. __new__函数

class Foo(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print(self.name, self.age)

    def tmp(self):
        print("call tmp()")

    def __new__(cls, *args, **kwargs):
        print("call __new__")
        obj = object.__new__(cls)
        print("id(obj)===", id(obj))
        return obj


f1 = Foo('Tim', 22) # 这一个操作,等于===下面的两步操作。
print("id(f1)===", id(f1))
f1.tmp()

#call __new__
#id(obj)=== 1507711426120
#Tim 22
#id(f1)=== 1507711426120
#call tmp()

f2 = Foo.__new__(Foo)
print("id(f2)===", id(f2))
f2.__init__('Tim', 22)
f2.tmp()

#call __new__
#id(obj)=== 1507711426232
#id(f2)=== 1507711426232
#Tim 22
#call tmp()
View Code

3. __init__函数

__init__函数,如果由Foo类能声明对象的时候,调用顺序是,先调用__new__,然后通过使用python提供的object.__new__方法,来创建一个对象,接下来把这个对象返回,然后由这个返回的对象,来调用__init__方法。

Foo.__new__ --> 通过object.__new__生产对象 --> 使用这个对象调用Foo.__init__方法-->完成类的对象声明

4. __metaclass__变量

ttt

猜你喜欢

转载自www.cnblogs.com/timlinux/p/9175543.html