英文:
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"getting {item}")
return super().__getattribute__(item)
class MyClass(metaclass=MyMeta):
my_class_attribute = "abc"
then
print(type(MyClass))
print(MyClass.my_class_attribute)
outputs
<class '__main__.MyMeta'>
getting my_class_attribute
abc
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论