Dynamically add methods to a class in Python 3.0

前端 未结 3 432
遥遥无期
遥遥无期 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:44

    Here is some working code to get you started (not the whole program you were trying to write, but something that shows how the parts can fit together):

    class Assign:
    
        def __init__(self, searchobj, key):
            self.searchobj = searchobj
            self.key = key
    
        def __call__(self, value):
            self.searchobj.conditions[self.key] = value
            return self.searchobj
    
    class Book():
    
        def __init__(self, family):
            self.family = family
            self.options = ['price', 'name', 'author', 'genre']
            self.conditions = {}
    
        def __getattr__(self, key):
            if key in self.options:
                return Assign(self, key)
            raise RuntimeError('There is no option for: %s' % key)
    
        def execute(self):
            # XXX do something with the conditions.
            return self.conditions
    
    b = Book('book')
    print(b.price(">4.00").author('J. K. Rowling').execute())
    

提交回复
热议问题