Classes can contain three types of methods:
Instance methods, e.g.
def imethod(self,...): ...
These can be called only on an instance of a class, and can access class and instance attributes. The first parameter is traditionally called self
and is automatically passed to the method when called on an instance:
instance = Class()
instance.imethod(...)
Class methods, e.g.
@classmethod
def cmethod(cls,...): ...
These can be called on the class itself or instances, but can only access class attributes. The first parameter is traditionally named cls
and is automatically passed to the method when called on a class:
Class.cmethod(...)
instance.cmethod(...) # works, but can't access instance attributes.
Static methods, e.g.
@staticmethod
def smethod(...): ...
These are functions related to the class, but can't access instance or class attributes, so they are not passed the class or instance object as the first parameter. They can be called on an instance or a class:
instance = Class()
Class.smethod(...)
instance.smethod(...)
Example (Python 3.9):
class Demo:
cvar = 1
def __init__(self,ivar):
self.ivar = ivar
@classmethod
def cmethod(cls):
print(f'{cls.cvar=}')
@staticmethod
def smethod():
print('static')
def imethod(self):
print(f'{self.cvar=} {self.ivar=}')
Demo.smethod()
Demo.cmethod()
instance = Demo(2)
instance.smethod()
instance.cmethod()
instance.imethod()
Output:
static
cls.cvar=1
static
cls.cvar=1
self.cvar=1 self.ivar=2
In your case, you defined an instance method, but didn't create an instance first, so the int
parameter you tried to pass was passed as self
, and internally tried to access actions
on the integer 50
. Create an instance first, and don't pass it any parameters. self
will be automatically passed:
compagnie = Compagnie('nom','actions','prix')
compagnie.setActions()