Vagabundo
Vagabundo

Reputation: 85

Dynamically adding descriptors to a class

I've a class with lots of attributes and to cut down on the complexity I'm trying to re-write it by dynamically creating them. I've tried the following:

class D_test: 
    def __get__(self, obj = None, obj_type= None): 
        print (f'{self} yeah!!') 
    def __set__(self, obj, value): 
        print (f'{self} {obj} {value}') 

class Blagh:
    pass

setattr(Blagh, 'test', D_test)

x = Blagh()

x.test

In [18]: x.test                                                                 
Out[18]: __main__.D_test


My understanding is that the above should call the __get__ of the descriptor. Where am I going wrong?

Upvotes: 1

Views: 39

Answers (1)

a_guest
a_guest

Reputation: 36249

You need to create an instance of the descriptor, otherwise you just attach the descriptor class to Blagh:

setattr(Blagh, 'test', D_test())

Upvotes: 2

Related Questions