I used to write classes with constant interface in C++ and want to ask you for advice: should I try to do it in my python programs?
Lets assume that I want to have immutable objects of class Point. Here is the C++ code:
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_;
};
Using objects of type Point I know that they will never change (I believe there are some hacks to do it, but it does not matter now).
In python I have several ways.
You are paranoid! Just keep it short and simple!
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
[+] Extremely clear code
[-] Does not solve the problem
Try to write only getters for class attributes.
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
[+] The leading underscore shows that attribute is "private"
[?] I don't think that it is a good idea to write the "imitation of C++-like code". Just because it is a different language.
[-] Attributes are still easy accessible. Should I name them with double underscore? (__x and __y)
One more way is to write decorator I found in this topic: 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
[+] Completely solves the problem (yes, I still can change values of x and y, but it becomes harder)
[?] Is it a python way at all?
[-] Too much code
So, my question is, what is the best practice?