When a function object (what the def
statement creates) is an attribute of a class AND is looked up (using the obj.attrname
scheme) on the class or an instance of the class, it gets turned into a method
object. This method
object is itself a callable. If the lookup happens on an instance, this instance will be "magically" inserted as the first argument to the function. If not, you will have to provide it by yourself (just like you would for any other argument).
You can read more about this (and how the "magic" happens here: https://wiki.python.org/moin/FromFunctionToMethod
In your case, you lookup the function on the class, so it expects two arguments (self
and param
), but you only pass param
, hence the error.
You defined variable_A
and variable_B
as class attributes (attributes that will be shared between all instances of the class). If that's really the intention, and you want a method you can call on the class itself and that will be able to access class attributes, you can make functionA
a classmethod
(it works the same as an "instance" method except it's the class that is 'magically' inserted as first argument):
class A(object):
variable_A = 1
variable_B = 2
@classmethod
def functionA(cls, param):
return param + cls.variable_A
Then you can call functionA
either directly on the class itself:
print(A.functionA(42))
or on an instance if you already have one at hand:
a = A()
# ...
print(a.functionA(42))
Now if you really wanted variable_A
and variable_B
to be per-instance attributes (each instance of A
has it's own distinct variables), you need to 1/ create those attributes on the instance itself in the initialier method and 2/ call functionA
on some A
instance, ie:
class A(object):
def __init__(self, variable_A=1, variable_B=2):
self.variable_A = variableA
self.variable_B = variableB
def functionA(self, param):
return param + self.variable_A
a1 = A() # using default values
print(a1.functionA(42))
a2 = A(5) # custom value for variable_A
print(a2.functionA(42))
A
is a class. You needA()
(instance ofA
). – Preform