Python元类

在Python当中万物皆对象,我们用class关键字定义的类本身也是一个对象,负责产生该对象的类称之为元类,元类可以简称为类的类,

元类的主要目的是为了控制类的创建行为.

type是Python的一个内建元类,用来直接控制生成类,在python当中任何class定义的类其实都是type类实例化的结果。

只有继承了type类才能称之为一个元类,否则就是一个普通的自定义类,自定义元类可以控制类的产生过程,类的产生过程其实就是元类的调用过程.

 

一个类由三大组成部分,分别是

1、类名class_name

2、继承关系class_bases

3、类的名称空间class_dict

方式1:使用class关键字(python解释器转化为第二种)

方式2:通过type关键字,依次传入以上三个参数即可。

方式一不讲了,下面方式二举例:

country = 'China'

def __init__(self, name, age):
    self.name = name
    self.age = age

def tell(self):
    print('%s 的年龄是:%s' % (self.name, self.age))

Person = type('Person', (object,), {'country': country, '__init__': __init__, 'tell': tell})
print(Person.__dict__)
person = Person('wtt', 25)
print(person.__dict__)
>>> {'country': 'China', '__init__': <function __init__ at 0x105e67268>, 'tell': <function tell at 0x105eac2f0>, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}

>>> {'name': 'wtt', 'age': 25}

Person 实际上就是一个类对象,于是我们将产生类的类称之为元类,默认的元类是type.

默认情况下,我们所说的元类都是指type这个元类,但是用户是可以自定义元类的,只要继承type就可以

class MyMetaClass(type):
    pass

country = 'China'

def __init__(self, name, age):
    self.name = name
    self.age = age

def tell(self):
    print('%s 的年龄是:%s' % (self.name, self.age))

Person = MyMetaClass('Person', (object,), {'country': country,'__init__': __init__, 'tell': tell})

print(Person.__dict__)
person = Person('wtt', 25)
print(person.__dict__)
>>> {'country': 'China', '__init__': <function __init__ at 0x105da3268>, 'tell': <function tell at 0x105de82f0>, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
>>> {'name': 'wtt', 'age': 25}

换种熟悉的格式:

class MyMetaClass(type):
    pass

class Person(object,metaclass=MyMetaClass): #自定义元类,来创建类.
    country = 'China'
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def tell(self):
        print('%s 的年龄是:%s'%(self.name,self.age))

print(Person.__dict__)
person = Person('wtt',25)
print(person.__dict__)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值