How to assign class method to class attribute?

This question already has an answer here:

  • Calling a function of a module by using its name (a string) 10 answers

  • Note that when you try:

    class A:
        MAP = {
            'add' : A.add(x, y),
            'subtract' : A.subtract(x, y),
        }
    

    you are trying to access eg A.add before the name A exists (the class isn't bound to the name until definition completes) and before the name add exists (you haven't defined that method yet). Everything at the top level of the class definition is done in order .


    You need to put the class methods into the dictionary after the class has been defined (they don't become callable until definition is complete):

    class A:
    
        MAP = {}
    
        @classmethod
        def add(cls, x, y):  # note colon
            return x + y
    
        @classmethod
        def subtract(cls, x, y):  # also here
            return x - y
    
    A.MAP['add'] = A.add
    A.MAP['subtract'] = A.subtract
    

    Note that, as neither class method uses cls , you could make them @staticmethod s instead. Or just use functions - Python isn't Java, you don't need to put everything into a class.


    Alternatively, you can use getattr to access attributes (including class methods) by name:

    >>> class A:
    
            @classmethod
            def add(cls, x, y):
                return x + y
    
            @classmethod
            def subtract(cls, x, y):
                return x - y
    
    
    >>> getattr(A, 'add')(1, 2)
    3
    

    请不要使用python编程,而应使用更标准的oop方法,例如:

    #!/usr/bin/env python
    
    class A:
    
        def __init__(self):
            pass
    
        @classmethod
        def add(self, x, y):
            return x + y
    
        @classmethod
        def subtract(self, x, y):
            return x - y
    
    if __name__ == "__main__":
        a = A()
        print a.add(1,2)  # ans: 3
        print a.subtract(2,1) # ans: 1
    
    链接地址: http://www.djcxy.com/p/55174.html

    上一篇: 从另一个文件和另一个类调用未指定的函数

    下一篇: 如何将类方法分配给类属性?