首页 > 文章列表 > Python元类的使用

Python元类的使用

Python元类
308 2022-08-07

1、说明

元类是类的类,是类的模板。元类的实例为类,正如类的实例为对象。

元类的作用就是用来创建类的。因为在子类中会继承元类,所以元类解决了代码冗余。

2、实例

>>> a =10; b = 12.12; c="hello" ;d =[1,2,3,"rr"];e = {"aa":1,"bb":"cc"}
>>> type(a);type(b);type(c);type(d);type(e)
<class 'int'>   #a = 10;a也是对象,即10是对象,是int类型的对象
<class 'float'> #float也是类,注意python很多类的写法是小写,有的则是大写
<class 'str'>
<class 'list'>
<class 'dict'>
 
 
class Person(object):
    print("不调用类,也会执行我")
    def __init__(self,name):
        self.name = name
    def p(self):
        print("this is a  methond")
        
print(Person)  
tom = Person("tom")
print("tom实例的类型是:%s"%type(tom))  # 实例tom是Person类的对象。
print("Peron类的类型:%s"%type(Person))  #结果看出我们创建的类属于type类,也就是说Person是type类的对象
print("type的类型是:%s"%type(type))  #type是type自己的对象
'''
不调用类,也会执行我
<class '__main__.Person'>
tom实例的类型是:<class '__main__.Person'>
Peron类的类型:<class 'type'>
type的类型是:<class 'type'>
'''

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。