Custom string representation of a Python Class property

与世无争的帅哥 提交于 2020-08-26 05:57:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!