没有'self'参数的函数在一个类中有什么意义?

zjm*_*126 6 python class

class a:
    def b():
        ...
Run Code Online (Sandbox Code Playgroud)

b的意义是什么?

谢谢


class a:
    @staticmethod    
    def b():
        return 1
    def c(self):
        b()

print a.b()
print a().b()
print a().c()#error
Run Code Online (Sandbox Code Playgroud)

class a:
    @staticmethod    
    def b():
        return 1
    def c(self):
        return self.b()

print a.b()
print a().b()
print a().c()
#1
#1
#1
Run Code Online (Sandbox Code Playgroud)

Vij*_*pte 7

基本上你应该使用b()作为staticmethod,这样你就可以从类的Class或Object中调用它,例如:

bash-3.2$ python
Python 2.6 (trunk:66714:66715M, Oct  1 2008, 18:36:04) 
[GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class a:
...    @staticmethod
...    def b():
...       return 1
... 
>>> a_obj = a()
>>> print a.b()
1
>>> print a_obj.b()
1
>>> 
Run Code Online (Sandbox Code Playgroud)