---
tags: Python
---
# Staticmethod and Classmethod in Python
author: [`ngokchaoho`](https://github.com/ngokchaoho)
After reading [Python Descriptors: An Introduction](https://realpython.com/python-descriptors/), I realise that
> Note that, in Python, a class method is just a static method that takes the class reference as the first argument of the argument list.
Hence I do the following experiment, since f in class A is static method, no arguemnt will be automatically supplied, Hence the number of argument is zero. You can use staticmethod with or without class, just note that it cannot access neither class attributes nor instance attrivutes hence both secret nor self._secret will be not available inside static method:
```python=
class A():
secret = 100
def __init__(self):
self._secret=43
@staticmethod
def f(*args):
print(secret)
A.f()
```
output:
```
Traceback (most recent call last):
File "<string>", line 9, in <module>
File "<string>", line 7, in f
NameError: name 'secret' is not defined
>
```
```python=
class A():
secret = 100
def __init__(self):
self._secret=43
@staticmethod
def f(self):
print(self._secret)
a = A()
a.f()
```
output
```
Traceback (most recent call last):
File "<string>", line 10, in <module>
TypeError: f() missing 1 required positional argument: 'self'
>
```
But a regular method would have the instance as the first argument:
```python=
class A():
secret = 100
def __init__(self):
self._secret=43
def f(*args):
print(args)
a = A()
a.f()
```
output:
```
(<__main__.A object at 0x7f393a2494c0>,)
```
now back to comparision between staticmethod and classmethod, as shown above static method doesn't have instance as the first argument automatically unlike regular method, so accessing via an instance or class both 0 arguments if you don't give it any. while classmethod would always have the type of the instance (or equivalently the class of the instance) as the first argument.
```python=
class A:
secret=43
def __init__(self):
self._secret = 43
@staticmethod
def f(*args):
print(len(args))
a = A()
a.f()
A.f()
A.f(1,2,3,4,5)
# Note that, in Python, a class method is just a static method that takes the class reference as the first argument of the argument list.
While
class B:
@classmethod
def f(*args):
print(len(args))
print(args[0])
b= B()
b.f()
B.f()
```
Output:
```
0
0
5
1
<class '__main__.B'>
1
<class '__main__.B'>
>
```