Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the significance of a function without a 'self' argument insde a class?

Tags:

python

class

class a:
    def b():
        ...

what is the Significance of b

thanks


class a:
    @staticmethod    
    def b():
        return 1
    def c(self):
        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
like image 875
zjm1126 Avatar asked Dec 26 '09 09:12

zjm1126


1 Answers

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
>>> 
like image 114
Vijayendra Bapte Avatar answered Nov 10 '22 04:11

Vijayendra Bapte