使用@property 与 getter 和 setter [英] Using @property versus getters and setters

查看:42
本文介绍了使用@property 与 getter 和 setter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个纯 Python 特定的设计问题:

Here is a pure Python-specific design question:

class MyClass(object):
    ...
    def get_my_attr(self):
        ...

    def set_my_attr(self, value):
        ...

class MyClass(object):
    ...        
    @property
    def my_attr(self):
        ...

    @my_attr.setter
    def my_attr(self, value):
        ...

Python 允许我们以任何一种方式进行.如果您要设计一个 Python 程序,您会使用哪种方法?为什么?

Python lets us to do it either way. If you would design a Python program, which approach would you use and why?

推荐答案

首选属性.这就是他们的目的.

原因是所有属性在 Python 中都是公开的.以一两个下划线开头的名称只是一个警告,即给定的属性是一个实现细节,在未来的代码版本中可能不会保持不变.它不会阻止您实际获取或设置该属性.因此,标准属性访问是访问属性的正常、Pythonic 方式.

The reason is that all attributes are public in Python. Starting names with an underscore or two is just a warning that the given attribute is an implementation detail that may not stay the same in future versions of the code. It doesn't prevent you from actually getting or setting that attribute. Therefore, standard attribute access is the normal, Pythonic way of, well, accessing attributes.

属性的优点是它们在语法上与属性访问相同,因此您可以从一种更改为另一种,而无需对客户端代码进行任何更改.您甚至可以拥有一个使用属性的类版本(例如,用于合同代码或调试)和一个不用于生产的类,而无需更改使用它的代码.同时,您不必为所有内容编写 getter 和 setter,以防您以后可能需要更好地控制访问.

The advantage of properties is that they are syntactically identical to attribute access, so you can change from one to another without any changes to client code. You could even have one version of a class that uses properties (say, for code-by-contract or debugging) and one that doesn't for production, without changing the code that uses it. At the same time, you don't have to write getters and setters for everything just in case you might need to better control access later.

这篇关于使用@property 与 getter 和 setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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