元类、创建类的方式

元类

注意:实例方法、类方法和静态方法都是保存在类的__dict__中的

简单来说,元类就是创建对象的类

可以通过__class__来查看实例对象的类以及类对象的类,请看下面代码

num = 10
print(num.__class__)

s = 'abc'
print(s.__class__)


class Person(object):
    pass


p = Person()
print(p.__class__)

print('-' * 20)

print(int.__class__)
# print(num.__class__.__class__)

print(str.__class__)
print(Person.__class__)


输出结果:
<class 'int'>
<class 'str'>
<class '__main__.Person'>
--------------------
<class 'type'>
<class 'type'>
<class 'type'>

反映在内存中可以这样表示:见下图

在这里插入图片描述
元类(type)上面就没有类了

创建类的方式

创建方式

  1. 通过class 定义
    当我们这么写这个类描述的时候, 解释器会自动的帮我们
    创建对应的类对象
  2. 通过type函数进行创建
# type函数进行创建类

def run(self):
    print('----', self)

# xxx 是一个存储类的地址的变量, Dog是类名
xxx = type('Dog', (), {'count': 0, 'run': run})
print(xxx)

print(xxx.__dict__)

d = xxx()
print(d)
d.run()

输出结果:

<class '__main__.Dog'>
{'count': 0, 'run': <function run at 0x000001CB68F8C1E0>, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'Dog' objects>, '__weakref__': <attribute '__weakref__' of 'Dog' objects>, '__doc__': None}
<__main__.Dog object at 0x000001CB69134240>
---- <__main__.Dog object at 0x000001CB69134240>

类的创建流程

  1. 检测类中是否有明确 __metaclass__属性 有, 则通过指定元类来创建这个类对象
  2. 检测父类中是否存在__metaclass__属性 有, 则通过指定元类来创建这个类对象
  3. 检测模块中是否存在__metaclass__属性 有, 则通过指定元类来创建这个类对象
  4. 通过内置的type这个元类,来创建这个类对象
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

*Heygirl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值