问题
I am defining a Class with several properties, most of which are int
or float
and for each I need to setup a specific string representation, is there an equivalent of __str__
or __repr__
for properties ?
UPDATE: to clarify, I'd like to have a custom string representation for my int
and float
values such as ' 022' or ' 3.27 ' related to the actual values, not just a static string for any value.
回答1:
You can create your own property object and override the intended methods. Here is an example:
In [48]: class MyProperty(property):
...: def __init__(self, *args, **kwargs):
...: super()
...: def __str__(self):
...: return "custom_name"
...:
In [49]:
In [49]: class C:
...: def __init__(self):
...: self._x = None
...:
...: @MyProperty
...: def x(self):
...: """I'm the 'x' property."""
...: return self._x
...:
...: @x.setter
...: def x(self, value):
...: self._x = value
...:
...: @x.deleter
...: def x(self):
...: del self._x
...:
In [50]:
In [50]: print(C.x)
custom_name
As another example you can find the callable object within args and preserve it for later in order to be able to access the name or ant other attribute of it that you're interested in.
In [78]: class MyProperty(property):
...: def __init__(self, *args, **kwargs):
...: self.__inp = next(i for i in args if isinstance(i, types.FunctionType))
...: super()
...:
...: def __str__(self):
...: return f"property name is : {self.__inp.__name__}"
Then:
In [80]: print(C.x)
property name is : x
来源:https://stackoverflow.com/questions/53649060/custom-string-representation-of-a-python-class-property