Generic methods in python

前端 未结 3 845
[愿得一人]
[愿得一人] 2021-02-08 14:20

Is it possible to implement generic method handlers in python which allow for calling of non-existent functions? Something like this:

class FooBar:
  def __gener         


        
相关标签:
3条回答
  • 2021-02-08 14:42
    class FooBar:
        def __getattr__(self, name):
            def foo():
                print name
            return foo
    
    a = FooBar()
    a.helloThere()
    
    0 讨论(0)
  • 2021-02-08 14:48

    The first thing to remember is that methods are attributes which happen to be callable.

    >>> s = " hello "
    >>> s.strip()
    'hello'
    >>> s.strip
    <built-in method strip of str object at 0x000000000223B9E0>
    

    So you can handle non-existent methods in the same way you would handle non-existent attributes.

    This is usally done by defining a __getattr__ method.

    Now you're going hit the additional complexity which is the difference between functions and method. Methods need to be bound to an object. You can take a look at this question for a discussion of this.

    So I think you'll want something like this:

    import types
    
    class SomeClass(object):
        def __init__(self,label):
            self.label = label
    
        def __str__(self):
            return self.label
    
        def __getattr__(self, name):
            # If name begins with f create a method
            if name.startswith('f'):
                def myfunc(self):
                    return "method " + name + " on SomeClass instance " + str(self)
                meth = types.MethodType(myfunc, self, SomeClass)
                return meth
            else:
                raise AttributeError()
    

    Which gives:

    >>> s = SomeClass("mytest")
    >>> s.f2()
    'method f2 on SomeClass instance mytest'
    >>> s.f2
    <bound method SomeClass.myfunc of <__main__.SomeClass object at 0x000000000233EC18>>
    

    However, I'd probably recommend against using this. If you tell us the problem you're trying to solve I expect someone here can come up with a better solution.

    0 讨论(0)
  • 2021-02-08 14:50
    def __getattr__(self, name):
      #return your function here...
    
    0 讨论(0)
提交回复
热议问题