dataclass装饰器
python3.7加入新module:dataclasses,就是你定义一个普通类,@dataclasses装饰器帮你生成__repr__、__init__等方法,不需要自己再写一遍了,此装饰器返回的依然是一个class。
from dataclasses import dataclass
@dataclass
class Dataclass1:
name: str = 'python'
strong_type: bool = True
static_type: bool = False
age: int = 28
@dataclasses会自动生成
def __init__(self, name: str = 'python',
strong_type: bool = True,
static_type: bool = False,
age: int = 28):
self.name = name
self.strong_type = strong_type
self.static_type = static_type
self.age = age
def __repr__(self):
return Dataclass1(name=self.name,
strong_type=self.strong_type,
static_type=self.static_type,
age=self.age)
def __eq__(self, other):
if other.__class__ is self.__class__:
return (self.name, self.strong_type, self.static_type, self.age) == (other.name, other.strong_type, other.static_type, other.age)
else:
return NotImplemented
def __ne__(self, other):
if other.__class__ is self.__class__:
return (self.name, self.strong_type, self.static_type, self.age) != (other.name, other.strong_type, other.static_type, other.age)
else:
return NotImplemented
def __lt__(self, other):
if other.__class__ is self.__class__:
return (self.name, self.strong_type, self.static_type, self.age) < (other.name, other.strong_type, other.static_type, other.age)
else:
return NotImplemented
def __le__(self, other):
if other.__class__ is self.__class__:
return (self.name, self.strong_type, self.static_type, self.age) <= (other.name, other.strong_type, other.static_type, other.age)
else:
return NotImplemented
def __gt__(self, other):
if other.__class__ is self.__class__:
return (self.name, self.strong_type, self.static_type, self.age) > (other.name, other.strong_type, other.static_type, other.age)
else:
return NotImplemented
def __ge__(self, other):
if other.__class__ is self.__class__:
return (self.name, self.strong_type, self.static_type, self.age) >= (other.name, other.strong_type, other.static_type, other.age)
else:
return NotImplemented
dataclasses的dataclass装饰器原型如下:
def dataclass(_cls=None, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
dataclasses.field
原型:
def field(*, default=MISSING, default_factory=MISSING, init=True, repr=True, hash=None, compare=True, metadata=None)
default和default_factory参数将会影响默认值的产生,default是field的默认值,而default_factory控制如何产生值,它接收一个无参数或者全是默认参数的callable对象,然后调用这个对象获得field的初始值,之后再将default(如何值不是MISSING)复制给callable返回的这个对象。
举例:
from dataclasses import dataclass, field
@dataclass
class Dataclass1:
mylist: list = field(default_factory=list)
dataclass1 = Dataclass1()
dataclass1.mylist += [1, 2, 3]
print(dataclass1.mylist)
dataclass2 = Dataclass1()
print(dataclass2.mylist)
当初始化Dataclass1的实例时就会调用list,而不是直接复制一份list的引用,避免了数据污染,执行结果:
[1, 2, 3]
[]
本文深入探讨了Python 3.7中引入的dataclasses模块,详细解释了如何使用@dataclass装饰器自动生成类的__init__、__repr__等方法,从而简化类的定义过程。此外,还介绍了如何通过dataclass的field函数定制字段属性。

2698

被折叠的 条评论
为什么被折叠?



