Skip to main content
 首页 » 编程设计

python之我应该在 Python 中实现具有常量接口(interface)的类吗

2024年11月01日12lovecherry

我曾经在 C++ 中编写具有常量接口(interface)的类,想向您请教:我应该尝试在我的 python 程序中这样做吗?

假设我想拥有 Point 类的不可变对象(immutable对象)。 这是 C++ 代码:

class Point 
{ 
public: 
    Point(double x, double y) : 
        x_{x}, 
        y_{y} 
    { } 
 
    double x() const { return x_; } 
    double y() const { return x_; } 
 
private: 
    double x_; 
    double y_; 
}; 

使用 Point 类型的对象我知道它们永远不会改变(我相信有一些 hack 可以做到这一点,但现在没关系)。

在 python 中我有几种方法。

你是偏执狂!保持简短!

from collections import namedtuple 
Point = namedtuple('Point', ['x', 'y']) 

[+] 非常清晰的代码

[-]没有解决问题

尝试只为类属性编写 getter。

class Point: 
    def __init__(self, x, y): 
        self._x = x 
        self._y = y 
 
    def x(self): 
        return self._x 
 
    def y(self): 
        return self._y 

[+] 前导下划线表示该属性是“私有(private)的”

[?] 我不认为编写“模仿类 C++ 代码”是个好主意。只是因为它是一种不同的语言。

[-] 属性仍然很容易访问。我应该用双下划线命名它们吗? (__x 和 __y)

另一种方法是编写我在本主题中找到的装饰器:How to create a constant in Python

def constant(f): 
    def fset(self, value): 
        raise SyntaxError 
    def fget(self): 
        return f() 
    return property(fget, fset) 
 
class Point: 
    ... 
    @constant 
    def x(self) 
        return self.__x 

[+] 完全解决了问题(是的,我仍然可以更改 x 和 y 的值,但变得更难了)

[?] 是 python 方式吗?

[-]代码过多

那么,我的问题是,最佳做法是什么?

请您参考如下方法:

我认为 namedtuple 正是您想要的:

>>> from collections import namedtuple 
>>> Point = namedtuple('Point', ['x', 'y']) 
>>> p = Point(10,20) 
>>> p.x 
10 
>>> p.y 
20 
>>> p.x = 100 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
AttributeError: can't set attribute