本文介绍了Python Class属性的自定义字符串表示形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在定义一个具有多个属性的类,其中大多数是 int float ,对于我需要的每个属性设置特定的字符串表示形式,是否有等效的 __ str __ __ repr __ 属性?

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 ?

更新:澄清一下,我想为 int float 值(例如022或3.27)与实际值相关,而不仅仅是任何值的静态字符串。

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.

推荐答案

您可以创建自己的属性对象并覆盖预期的方法。下面是一个示例:

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

作为另一个示例可以在args中找到可调用对象并将其保存以备后用为了能够访问您感兴趣的名称或其他属性。

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__}"

然后:

In [80]: print(C.x)
property name is : x

这篇关于Python Class属性的自定义字符串表示形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 12:34