In the following code why does the last line of execution give an error ? Shouldn't the dot operator in x.bf() pass on the instance 'x' to the function bf ( like x.af() would ) ?
a = 6
def af (self):
b = 7
def bf (self):
>>> x = A()
>>> b = B()
>>> x.bf = B.bf
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bf() missing 1 required positional argument: 'self'
Best How To :
x.bf = B.bf is your error, because B is a class, not an instance of the object.
You can't assign x.bf directly to the class. You need to assign x.bf to the instance 'b.bf' or instantiate the class properly
ie. Either change that line to:
# Where we instantiated class B and invoke bf via lazy loading (loading at the last possible minute)
x.bf = B().bf
# Use the existing instance of B and call bf
x.bf = b.bf
- A and B are your classes. They don't do anything until you instantiate them.
- x and b are your object instances. x is an instance of A, and b is an instance of B
Whenever you instantiate a class, you need to conform to it's constructor signature. In this case, the classes require no additional parameters besides self. However, self only gets passed if the class is invoked via ();
'x = A()' and 'b = B()' conform to that signature
The error you encountered is basically python telling you that you called something, a function or a class without passing in a required variable.