简体   繁体   English

Python:在访问任何类属性时调用一个函数

[英]Python: call a function on access of any class attribute

This is a little hard to explain but here is what I want to do: I want to create a function / property on my class that will do the following. 这有点难以解释,但这是我想做的:我想在我的类上创建一个函数/属性,该函数/属性将执行以下操作。 No matter what field I access it compares the value of that field to the rest of the attributes and returns something. 无论我访问哪个字段,它都会将该字段的值与其余属性进行比较,并返回结果。

For example: 例如:

class myClass(object):
    a = 1
    b = 2
    c = 3

    def myProp(sef, accessed_attribute):
        return someting like you accessed <name of attrib>  and it is the largest value of all all of the attribues" 

basically it compares the value to the rest of the attributes without having to write a property for each attribute. 基本上,它将值与其余属性进行比较,而不必为每个属性编写一个属性。

如果要在访问类属性(而不是实例属性)时调用此函数,则可以为类使用自定义元类,并在此元类中重写__getattribute__方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM