Python数据类和属性装饰器 [英] Python Dataclass and property decorator

查看:177
本文介绍了Python数据类和属性装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读Python 3.7的数据类,以替代namedtuple(当我必须在结构中对数据进行分组时通常使用的).我想知道dataclass是否与属性装饰器兼容,以便为dataclass的数据元素定义getter和setter函数.如果是这样,这在某处有描述吗?还是有可用的示例?

I've been reading up on Python 3.7's dataclass as an alternative to namedtuples (what I typically use when having to group data in a structure). I was wondering if dataclass is compatible with the property decorator to define getter and setter functions for the data elements of the dataclass. If so, is this described somewhere? Or are there examples available?

推荐答案

确定有效:

from dataclasses import dataclass

@dataclass
class Test:
    _name: str="schbell"

    @property
    def name(self) -> str:
        return self._name

    @name.setter
    def name(self, v: str) -> None:
        self._name = v

t = Test()
print(t.name) # schbell
t.name = "flirp"
print(t.name) # flirp
print(t) # Test(_name='flirp')

实际上,为什么不呢?最后,您得到的只是一个很好的旧类,它是从type派生的:

In fact, why should it not? In the end, what you get is just a good old class, derived from type:

print(type(t)) # <class '__main__.Test'>
print(type(Test)) # <class 'type'>

也许这就是为什么没有特别提到属性的原因.但是, PEP-557的摘要提到了已知的Python类功能:

Maybe that's why properties are nowhere mentioned specifically. However, the PEP-557's Abstract mentions the general usability of well-known Python class features:

由于数据类使用常规的类定义语法,因此您很自由 使用继承,元类,文档字符串,用户定义的方法, 类工厂和其他Python类功能.

Because Data Classes use normal class definition syntax, you are free to use inheritance, metaclasses, docstrings, user-defined methods, class factories, and other Python class features.

这篇关于Python数据类和属性装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆