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

6 投票
3 回答
8183 浏览
提问于 2025-04-15 17:22
class a:
    def b():
        ...

b的意义是什么?

谢谢!


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

print a.b()
print a().b()
print a().c()#error

还有

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

3 个回答

1

在一个类的方法中,self 是调用这个方法的类的实例。要注意的是,self 不是 Python 的关键字,只是一个约定俗成的名字,用来表示方法的第一个参数。

看看这个例子:

class A:

    def foo(self):
        print "I'm a.foo"

    @staticmethod
    def bar(s):
        print s

a = A()
a.foo()
A.foo(a)

这里的 a 是类 A 的一个实例。当你调用 a.foo() 时,你是在调用实例 a 的方法 foo。而 A.foo(a) 则是在调用类 A 的方法 foo,但把实例 a 作为第一个参数传进去,这两者实际上是完全一样的(不过最好不要使用第二种形式)。

staticmethod 是一个装饰器,它让你可以把一个类的方法定义为静态方法。这个函数就不再是一个方法了,第一参数也不再是类的实例,而是你传给这个函数的第一个参数:

a.bar("i'm a static method")
i'm a static method
A.bar("i'm a static method too")
i'm a static method too

顺便说一下,我不想打扰你,但这些都是 Python 的基础知识,Python 教程 是初学者的一个不错的起点。

4

语法错误。试着调用它。

>>> class a:
...     def b():
...             return 1
... 
>>> x=a()
>>> x.b()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: b() takes no arguments (1 given)

另请参见:

>>> class a:
...     def b():
...             return 1
...     def c(self):
...             return b()
... 
>>> a().c()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in c
NameError: global name 'b' is not defined
7

基本上,你应该把 b() 定义为静态方法,这样你就可以通过类名或者类的对象来调用它,比如:

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
>>> 

撰写回答