What is the significance of a function without a 'self' argument insde a class?
class a:
def b():
...
what is the Significance of b
thanks
class a:
@staticmethod
def b():
return 1
def c(sel开发者_运维百科f):
b()
print a.b()
print a().b()
print a().c()#error
and
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
Basically you should use b() as staticmethod so that you can call it either from Class or Object of class e.g:
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
>>>
Syntax error. Try calling it.
>>> 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)
See also:
>>> 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
in a class method self
is the instance of the class the method is called on. beware that self
is not a keyword in python just a conventional name given to the first argument of a method.
look at this example:
class A:
def foo(self):
print "I'm a.foo"
@staticmethod
def bar(s):
print s
a = A()
a.foo()
A.foo(a)
here a
is the instance of the class A
. calling a.foo()
you are invoking the method foo
of the instance a
while A.foo(a)
invoke the method foo
in the class A
but passing the instance a
as first argument and they are exactly the same thing (but never use the second form).
staticmethod
is a decorator that let you define a class method as static. that function is no more a method and the first argument is not the instance of the class but is exactly the first argument you passed at that function:
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
PS. i don't want to bothering you but these are the very basis of python, the python tutorial is a nice start for the beginners.
精彩评论