Python之metaclass和dataclass
创始人
2024-05-30 00:17:18
0

metaclass:

MetaClass元类,本质也是一个类,但和普通类的用法不同,它可以对类内部的定义(包括类属性和类方法)进行动态的修改。可以这么说,使用元类的主要目的就是为了实现在创建类时,能够动态地改变类中定义的属性或者方法。

举个例子,根据实际场景的需要,我们要为多个类添加一个 name 属性和一个 say() 方法。显然有多种方法可以实现,但其中一种方法就是使用 MetaClass 元类。

如果在创建类时,想用 MetaClass 元类动态地修改内部的属性或者方法,则类的创建过程将变得复杂:先创建 MetaClass 元类,然后用元类去创建类,最后使用该类的实例化对象实现功能。

如果想把一个类设计成 MetaClass 元类,其必须符合以下条件:

  1. 必须显式继承自 type 类;

  1. 类中需要定义并实现 __new__() 方法,该方法一定要返回该类的一个实例对象,因为在使用元类创建类时,该 __new__() 方法会自动被执行,用来修改新建的类。

metaclass 是 type 的子类,通过替换 type的__call__运算符重载机制,“超越变形”正常的类。

一旦你把一个类型 Student 的 metaclass 设置成 Human,Student 就不再由原生的 type创建:

class Human(type):def __new__(mcs, *args, **kwargs):class_ = super().__new__(mcs, *args)for key, value in kwargs.items():setattr(class_, key, value)return class_class Student(object, metaclass=Human, country="China", freedom=True):passprint(Student.freedom)
print(Student.country)

实现一个根据props = ["name", "age"] 动态添加实例属性的metaclass:Human

class Prop:def __init__(self, attr):self._attr = f"_{attr}"def get(self, obj):if not hasattr(obj, self._attr):return Nonereturn getattr(obj, self._attr)def set(self, obj, value):setattr(obj, self._attr, value)class Human(type):def __new__(mcs, *args, **kwargs):class_ = super().__new__(mcs, *args)for property_name in class_.props:prop = Prop(property_name)prop_value = property(fget=prop.get, fset=prop.set)setattr(class_, property_name, prop_value)return class_class Student(object, metaclass=Human):props = ["name", "age"]student = Student()print(student.name)
student.name = "KbZswWtl"
print(student.name)

用装饰器的形式来进行metadata的封装:

class Prop:def __init__(self, attr):self._attr = f"_{attr}"def get(self, obj):if not hasattr(obj, self._attr):return Nonereturn getattr(obj, self._attr)def set(self, obj, value):setattr(obj, self._attr, value)class Human(type):def __new__(mcs, *args, **kwargs):class_ = super().__new__(mcs, *args)for property_name in class_.props:prop = Prop(property_name)prop_value = property(fget=prop.get, fset=prop.set)setattr(class_, property_name, prop_value)return class_def human(cls):return Human(cls.__name__, cls.__bases__, dict(cls.__dict__))class Student(object, metaclass=Human):props = ["name", "age"]@human
class Man:props = ["name", "age"]man = Man()
print(man.name)
man.name = "Tom"
print(man.name)student = Student()print(student.name)
student.name = "KbZswWtl"
print(student.name)

dataclass:

Python 内置装饰器可降低代码的复杂性和长度

Python中的面向对象编程(OOP)一直是热门话题之一。这是因为 Python 之所以出名,是因为它的灵活性和开箱即用的特性可以在很大程度上减少开发工作量,OOP 也是如此。

他们都需要利用 3rd 方库,但它们仍然是很好的解决方案。

这里介绍一个 Python 内置模块——Dataclass。它是在 Python 3.7 中引入的,它使开发人员能够以面向对象的方式进行编码,而无需任何 3rd 方库。数据类提供了开箱即用的方法来创建自定义数据, 可以直接实例化、打印和比较数据类实例。

from dataclasses import dataclass@dataclass
class Student:name: strage: ints_1 = Student()

从上面可以看出,@dataclass装饰器给我们的类中自动添加了__init__(self,name,age)函数

from dataclasses import dataclass@dataclass
class Student:name: strage: ints_1 = Student("KbZswWtl", 31)
s_2 = Student("KbZswWtl", 31)print(s_1)
print(s_2)print(s_1 == s_2)

从上面可以看出,@dataclass装饰器也给我们的类中添加了__str__、判等的函数

from dataclasses import dataclass@dataclass
class Student:name: strage: int = 18s_1 = Student("KbZswWtl")
s_2 = Student("KbZswWtl")print(s_1)
print(s_2)

从上面可以看出,@dataclass装饰器也给我们的类中添加了__init__默认值的操作

相关内容

热门资讯

苹果怎么倒进安卓系统,一键倒装... 你有没有想过,把苹果手机里的宝贝倒腾到安卓系统里去?听起来是不是有点像变魔术?别急,今天就来手把手教...
安卓系统都能双系统么吗,揭秘双... 你有没有想过,你的安卓手机是不是也能来个“双胞胎”呢?没错,就是那种一个手机里同时运行两个操作系统,...
长安汽车升级安卓系统,安卓系统... 你知道吗?最近长安汽车可是来了一次大变身呢!没错,就是那个我们熟悉的国产汽车品牌,这次他们竟然升级了...
mac电脑装安卓系统,轻松实现... 亲爱的电脑迷们,你是否曾幻想过在你的Mac电脑上运行安卓系统?想象那些你钟爱的安卓应用,在你的Mac...
安卓p系统流畅吗,畅享无忧 你有没有发现,最近安卓P系统成了大家热议的话题呢?不少朋友都在问,这个新系统到底流畅不流畅啊?今天,...
剑灵2安卓系统,畅游东方奇幻世... 你知道吗?最近在安卓系统上,有一款游戏可是火得一塌糊涂,那就是《剑灵2》!这款游戏不仅画面精美,操作...
安卓系统是否指定品牌,品牌定制... 你有没有想过,为什么你的安卓手机总是那么独特,而别人的安卓手机却看起来差不多呢?这背后,其实隐藏着一...
安卓系统和iso系统 照片共享... 你有没有发现,现在手机拍照功能越来越强大,拍出来的照片美得不要不要的!但是,当你想和朋友们分享这些精...
安卓系统领夹麦,便携式音频解决... 你有没有发现,现在手机通话越来越方便了,但是有时候,手机那点小小的麦克风,真的有点力不从心呢!尤其是...
安卓系统经常无法唤醒,探究系统... 你是不是也遇到过这种情况?手机屏幕黑了,手指在屏幕上疯狂地滑动,却怎么也唤醒不了安卓系统。这可真是让...
自己编译安卓系统源码,编译安卓... 你有没有想过,安卓系统其实就像一个巨大的宝藏,里面藏着无数的秘密和可能性?今天,就让我带你一起探索这...
鸿蒙系统属于安卓,基于安卓的全... 你知道吗?最近有个话题在科技圈里可是闹得沸沸扬扬的,那就是鸿蒙系统。没错,就是那个华为自主研发的操作...
lephone是安卓系统吗,深... 你有没有听说过lephone这个品牌呢?最近,身边的朋友都在讨论这个手机,说它性价比超高,但是,有人...
pc双系统安卓系统下载软件,P... 你有没有想过,在电脑上同时运行安卓系统,是不是就像在手机上玩电脑游戏一样酷炫呢?没错,这就是今天我要...
电量壁纸安卓系统设置,安卓系统... 手机电量告急,是不是又得赶紧找充电宝了?别急,今天就来和你聊聊如何通过设置电量壁纸来给安卓系统来个“...
ip是安卓系统吗,通过IP地址... 你有没有想过,那个陪伴你每天刷剧、玩游戏、办公的IP,它是不是安卓系统呢?别急,今天就来揭开这个谜底...
安卓系统谁负责升级,揭秘幕后负... 你有没有想过,你的安卓手机为什么有时候会突然收到系统更新的通知呢?是不是好奇,是谁在背后默默地为你的...
安卓系统需要降级吗,安卓系统升... 你有没有发现,你的安卓手机最近有点儿“老态龙钟”了呢?运行速度慢吞吞的,有时候还卡个不停。这时候,你...
性价比手机安卓系统,盘点安卓系... 你有没有想过,在这个手机更新换代如此迅速的时代,如何用最少的钱,买到最满意的手机呢?没错,我要说的是...
虚拟大师安卓2.0系统,安卓新... 你有没有听说最近虚拟大师安卓2.0系统火得一塌糊涂?这可不是空穴来风,而是真的让不少手机用户都跃跃欲...