使用点表示法访问 `MyClass.my_attribute` 时调用了哪个方法?

huangapple go评论61阅读模式
英文:

What method is called when using dot notation in MyClass.my_attribute?

问题

我想要在使用点表示法获取属性时打印"获取 x 属性"。

例如:

class MyClass:
   my_attribute = "abc"

print(MyClass.my_attribute)

我期望它的输出如下:

>>> 获取 my_attribute 属性
>>> abc

我没有实例化该类。
我尝试在MyClass.__getattr__()MyClass.__getattribute__()中添加打印语句,但这两者都不会显示任何内容。

我尝试了以下方法:

class MyClass:
    def __getattr__(self, key):
        print("运行 __getattr__")
        return super().__getattr__(key)
    
    def __getattribute__(self, __name: str) -> Any:
        print("运行 __getattribute__")
        return super().__getattribute__(__name)

    my_attribute = "abc"
英文:

I want to print "getting x attr" whenever I use the dot notation to get an attribute.

For example

class MyClass:
   my_attribute = "abc"

print(MyClass.my_attribute)

I'd expect it to output like this:

>>> getting my_attribute attr
>>> abc

I'm not instantiating the class.
I tried to add a print statement to MyClass.__getattr__() and MyClass.__getattribute__() but none of these will display anything.

I tried the following:

class MyClass:
    def __getattr__(self, key):
        print("running __getattr__")
        return super().__getattr__(key)
    
    def __getattribute__(self, __name: str) -> Any:
        print("running __getattribute__")
        return super().__getattribute__(__name)

    my_attribute = "abc"

答案1

得分: 4

MyClass(类对象本身)本身就是一个对象。您想在类MyClass的实例上定义自己的__getattribute__方法。要做到这一点,可以使用元类

class MyMeta(type):

    def __getattribute__(self, item):
        print(f"获取 {item}")
        return super().__getattribute__(item)


class MyClass(metaclass=MyMeta):
    my_class_attribute = "abc"

然后

print(type(MyClass))
print(MyClass.my_class_attribute)

输出

<class '__main__.MyMeta'>
获取 my_class_attribute
abc
英文:

MyClass (the class object) is itself an object. You want to define your custom __getattribute__ method on the class that MyClass is an instance of. To do that, use a metaclass:

class MyMeta(type):

    def __getattribute__(self, item):
        print(f&quot;getting {item}&quot;)
        return super().__getattribute__(item)


class MyClass(metaclass=MyMeta):
    my_class_attribute = &quot;abc&quot;

then

print(type(MyClass))
print(MyClass.my_class_attribute)

outputs

&lt;class &#39;__main__.MyMeta&#39;&gt;
getting my_class_attribute
abc

huangapple
  • 本文由 发表于 2023年6月29日 22:50:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76582211.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定