简体   繁体   English

动态地向类添加描述符

[英]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.我的理解是上面应该调用描述符的__get__ Where am I going wrong?我哪里错了?

您需要创建描述符的实例,否则您只需将描述符类附加到Blagh

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

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

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