品易云推流 关闭
文章详情页
文章 > Python基础教程 > Python元类的使用

Python元类的使用

头像

小妮浅浅

2021-05-28 09:32:262315浏览 · 0收藏 · 0评论

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'>
'''

以上就是Python元类的使用,希望对大家有所帮助。更多Python学习推荐:python教学

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

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图