Python学习笔记二十四( 元类 )

__class__属性

__class__属性可以查看对象的类型.

class Person(object):
    pass


person = Person()

print(person.__class__)

# 运行结果
# <class '__main__.Person'>

Person 类的实例对象person 的类型时Person 类类型, Python 是面向对象的语言, 那么Person 的类对象的类型又是什么?

class Person(object):
    pass


person = Person()

print(person.__class__)
print(Person.__class__)

# int 的类型
print(int.__class__)
# str 的类型
print(str.__class__)

# 运行结果
# <class '__main__.Person'>
# <class 'type'>
# <class 'type'>
# <class 'type'>

Person / int / str 的类对象的类型都是type 类类型.
那么type类对象 的类型又是什么类型?

class Person(object):
    pass


print(Person.__class__.__class__)

# int 的类型
print(int.__class__.__class__)
# str 的类型
print(str.__class__.__class__)
print(type.__class__)

# 运行结果
# <class 'type'>
# <class 'type'>
# <class 'type'>
# <class 'type'>

type 类对象的类型还是type 类类型, 那么type 类是干嘛的?

元类

type 类是元类, Python中所有的类默认都是使用type 类创建的, type 类属于Python中的高深魔法, 一般很少用到.

   """
    type(object_or_name, bases, dict)
    type(object) -> the object's type
    type(name, bases, dict) -> a new type
    """

type类有两个功能,

  • type(object) : 一个参数,返回object 的类型
  • type(name, bases, dict) : 三个参数,返回一个新的类型
type(object)
class Person(object):
    pass


person = Person()

print(type(person))  # 查看person 实例对象的类型
print(type(Person))  # 查看Person 类对象的类型

# 运行结果
# <class '__main__.Person'>
# <class 'type'>
type(name, bases, dict)

使用type 创建一个类

正常创建Person 类的子类Teacher

class Person(object):
    pass


class Teacher(Person):
    def __init__(self):
        self.name = "Teacher"


# help() 函数用于查看函数或模块用途的详细说明。
print(help(Teacher))

元类创建Person 类的子类Student

class Person(object):
    pass


def __init__(self):
    self.name = "Student"

# "Student" 是类名
Student = type("Student", (Person,), {"__init__": __init__})
# help() 函数用于查看函数或模块用途的详细说明。
print(help(Student))

运行结果对比

《Python学习笔记二十四( 元类 )》 01对比.png

元类创建类
class Person(object):
    pass


def __init__(self):
    pass


@classmethod
def test_cls_func(cls):
    pass


@staticmethod
def test_static_func():
    pass


Student = type(
    "Student",  # 类名
    (Person,),  # 所有的父类,使用元组传参

    {"__init__": __init__,  # 实例方法
     "test_cls_func": test_cls_func,  # 类方法
     "test_static_func": test_static_func,  # 静态方法
     "type_name": "student",  # 类属性
     }  # 类包含的属性
)

print(help(Student))

# 运行结果
# {'__init__': <function __init__ at 0x0000016D93862E18>,
# 'test_cls_func': <classmethod object at 0x0000016D95716400>,
# 'test_static_func': <staticmethod object at 0x0000016D95716BA8>,
# 'type_name': 'student',
# '__module__': '__main__',
# '__doc__': None}

运行结果

《Python学习笔记二十四( 元类 )》 02运行结果.png

注意:

class Person(object):
    pass

# Student 只是一个变量,引用了type 返回的Student类型
Student = type("Student", (Person,), {"type_name": "student", })
student = Student()

# Student2 只是一个变量,引用了type 返回的Student类型
Student2 = type("Student", (Person,), {"type_name": "student", })
student2 = Student2()

print(type(student))
print(type(student2))

# 运行结果
# <class '__main__.Student'>
# <class '__main__.Student'>

元类改造类

元类除了能创建一个类,也能改造一个类.

class ChangeClass(type):  # 这个必须是type子类
    def __new__(cls, class_name, super_names, attrs):
        print("class_name: %s" % class_name)
        print("super_names: %s" % super_names)
        print("attrs: %s" % attrs)

        tmp_attrs = dict()

        # 将所有 实例/类/静态 方法的名字改为小写
        for key, value in attrs.items():

            # hasattr(value, "__call__")  判断值是一个func 对象,
            # 不能使用isinstance , 因为 class function: # TODO not defined in builtins!(源码)
            if hasattr(value, "__call__") or isinstance(value, classmethod) or isinstance(value, staticmethod):
                tmp_attrs[key.lower()] = value
                continue
            tmp_attrs[key] = value

        return type.__new__(cls, class_name, super_names, tmp_attrs)  # 一般工作中用这种方式


class Preson(object, metaclass=ChangeClass):
    cls_name = "cls_name"

    def __init__(self):
        self.self_name = "self_name"

    @classmethod
    def Test_Cls_Func(cls):
        pass


print("改造后 " + "*" * 20)
print(Preson.__dict__)
# 运行结果
# class_name: Preson
# super_names: <class 'object'>
# attrs: {'__module__': '__main__', '__qualname__': 'Preson', 'cls_name': 'cls_name', 
#       '__init__': <function Preson.__init__ at 0x000002260B828A60>, 
#       'Test_Cls_Func': <classmethod object at 0x000002260B826F28>}
# 改造后 ********************
# {'__module__': '__main__', 'cls_name': 'cls_name', 
#       '__init__': <function Preson.__init__ at 0x000002260B828A60>, 
#       'test_cls_func': <classmethod object at 0x000002260B826F28>, 
#       '__dict__': <attribute '__dict__' of 'Preson' objects>, 
#       '__weakref__': <attribute '__weakref__' of 'Preson' objects>, '__doc__': None}

结语

经过近两个月的努力, 写下了Python 学习笔记系列共计二十四篇, 限于本人精力以及能力, 篇章中如有错误之处, 烦请各位告知, 便于更正, 以利他人.

是结束亦是开始, 革命尚未成功, 同志仍需努力.

Html / Css / JavaScript 学习 : w3school 在线教程
Python 教程 : 廖雪峰 Python 教程
菜鸟教程

到此结  DragonFangQy 2018.5.27

    原文作者:DragonFangQy
    原文地址: https://www.jianshu.com/p/10f33d320b04
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞