0

假设我有一堂课:

class Test:

 def __init__(self):
    self.value = 1;

test = Test();

value是否可以在访问对象本身时指定一种默认访问方式?例如:

a = 1 + test   # by default this would be equivalent to a = 1 + test.value

这个问题的原因是我有一些带有内置验证的标准对象,我几乎总是只能从中获取value属性。目的只是为了减少混乱。

一位用户建议覆盖特定的必要操作,但在我发表评论之前,答案已被删除。这也许可行,但我想知道在一般层面上是否可行。

4

1 回答 1

0

我认为这不是合适的方式,因为默认情况下,如果 Python 类None被初始化,它将返回。但如果你还想做。您可以使用__new__代替__init__

class Test:
    def __new__(cls):
        cls.value = 1
        return cls.value

test = Test()
print(test)

输出:

1
于 2021-06-26T01:38:37.590 回答