Dynamically add methods to a class in Python 3.0

前端 未结 3 421
遥遥无期
遥遥无期 2021-02-06 01:10

I\'m trying to write a Database Abstraction Layer in Python which lets you construct SQL statments using chained function calls such as:

results = db.search(\"bo         


        
3条回答
  •  伪装坚强ぢ
    2021-02-06 01:46

    Firstly, you are not adding anything to the class, you are adding it to the instance.

    Secondly, you don't need to access dict. The self.__dict__[opt] = self.__Set__ is better done with setattr(self, opt, self.__Set__).

    Thirdly, don't use __xxx__ as attribute names. Those are reserved for Python-internal use.

    Fourthly, as you noticed, Python is not easily fooled. The internal name of the method you call is still __Set__, even though you access it under a different name. :-) The name is set when you define the method as a part of the def statement.

    You probably want to create and set the options methods with a metaclass. You also might want to actually create those methods instead of trying to use one method for all of them. If you really want to use only one __getattr__ is the way, but it can be a bit fiddly, I generally recommend against it. Lambdas or other dynamically generated methods are probably better.

提交回复
热议问题