直接访问实例获取class的属性

Get attribute of class by directly accessing instance

我想知道如何 "call" 一个 class 的实例,使得该实例本身 return 是一个特定的值、属性或方法 return。
我试着用一个例子来说明这一点:

import numpy as np

class MyClass():
    def __init__(self, x):
        self.x = x
        self.y = self.x*2
        self.z = self.x*3


    def __call_instance__(self):
        return np.eye(2)*self.x


def some_function(x, y, z):
    return x, y, z


inst = MyClass(3)

some_function(x=inst, y=inst.y, z=inst.z)

Out[1]:
(array([[ 3.,  0.],
        [ 0.,  3.]]), 6, 9)

我知道我可以将__call__()定义为方法并通过inst()调用实例。但是有没有办法通过 "calling" 没有括号的实例来使用特定方法或特定属性的 return ?换句话说,这样实例本身就像一个 attribute/property 本身一样? 我希望如果能说清楚我在寻找什么:-)

期待您的回答。 干杯,提前谢谢你。

马库斯

But is there a way to use the return of a specific method or a certain attribute by just "calling" the instance without the parenthesis?

通过键入实例名称,无需其他任何内容,您只是在询问实例(更准确地说,您是在询问绑定到实例的变量的值)。您可以调用多种方法 - 调用覆盖运算符、打印 __str__ 覆盖、__call__ 调用。

但是,如果您覆盖其中一种方法的名称,您希望如何访问该实例?


>>> l = [1, 2, 3]
>>> l = l.pop
# How can you access the original list?