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

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

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

问题

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

例如:

  1. class MyClass:
  2. my_attribute = "abc"
  3. print(MyClass.my_attribute)

我期望它的输出如下:

  1. >>> 获取 my_attribute 属性
  2. >>> abc

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

我尝试了以下方法:

  1. class MyClass:
  2. def __getattr__(self, key):
  3. print("运行 __getattr__")
  4. return super().__getattr__(key)
  5. def __getattribute__(self, __name: str) -> Any:
  6. print("运行 __getattribute__")
  7. return super().__getattribute__(__name)
  8. my_attribute = "abc"
英文:

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

For example

  1. class MyClass:
  2. my_attribute = "abc"
  3. print(MyClass.my_attribute)

I'd expect it to output like this:

  1. >>> getting my_attribute attr
  2. >>> 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:

  1. class MyClass:
  2. def __getattr__(self, key):
  3. print("running __getattr__")
  4. return super().__getattr__(key)
  5. def __getattribute__(self, __name: str) -> Any:
  6. print("running __getattribute__")
  7. return super().__getattribute__(__name)
  8. my_attribute = "abc"

答案1

得分: 4

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

  1. class MyMeta(type):
  2. def __getattribute__(self, item):
  3. print(f"获取 {item}")
  4. return super().__getattribute__(item)
  5. class MyClass(metaclass=MyMeta):
  6. my_class_attribute = "abc"

然后

  1. print(type(MyClass))
  2. print(MyClass.my_class_attribute)

输出

  1. <class '__main__.MyMeta'>
  2. 获取 my_class_attribute
  3. 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:

  1. class MyMeta(type):
  2. def __getattribute__(self, item):
  3. print(f&quot;getting {item}&quot;)
  4. return super().__getattribute__(item)
  5. class MyClass(metaclass=MyMeta):
  6. my_class_attribute = &quot;abc&quot;

then

  1. print(type(MyClass))
  2. print(MyClass.my_class_attribute)

outputs

  1. &lt;class &#39;__main__.MyMeta&#39;&gt;
  2. getting my_class_attribute
  3. 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:

确定