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

查看:53
本文介绍了使用@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?

推荐答案

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

Prefer properties. It's what they're there for.

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

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天全站免登陆