__getattr__ in the class, not (or how) an instance

I know that I can write code like:

class A : def __getattr__ (self, name) : return name 

to catch access to undefined attributes for an instance of the class, therefore:

 A().ATTR == 'ATTR' 

- it's true. But is there a way to do this for the class itself? What I would like to have is to have the following two lines and work, and be distinguishable (i.e. there are different magic methods, or the magic method can determine how it was called)

 a = A().ATTR b = A.ATTR 

I suspect there is no answer, but maybe there is some kind of deep python ju-ju?

Change The actual problem is expanding the user library of the active record in a backward compatible way. ORM code supports code in lines

 ar = AR_people() ar.find() name = ar.name 

to access tables where name can be mapped to a column name that is different, for example. pe_name . We want to write something like

 ar.filter(AR_people.age >= 21) 

and in the end

 pe_age >= 21 

(like other ORM libraries), so AR_people.age must return an instance of a class that implements __ge__ , etc., to do the magic of conversion.

+4
source share
2 answers

You can use the metaclass :

 In [1]: class meta(type): ...: def __getattr__(self, name): ...: return name ...: ...: In [2]: class A(object): ...: __metaclass__ = meta ...: def __getattr__(self, name): ...: return name ...: ...: In [3]: A().attr Out[3]: 'attr' In [4]: A.attr Out[4]: 'attr' 
+7
source

Yes, you can. Metaclasses are the answer.

 class MyMetaclass(type): def __getattr__(cls, name): return "cls.%s" % name class A : __metaclass__ = MyMetaclass def __getattr__ (self, name) : return name print A().ATTR print A.ATTR 

displays

 ATTR cls.ATTR 
+2
source

All Articles