user3260901
user3260901

Reputation: 79

In the following code why does the last line of execution give an error?

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 ) ?

class A:
    a = 6
    def af (self):
        return "Hello-People"

class B:
    b = 7
    def bf (self):
        return "Bye-People"

>>> x = A()
>>> b = B()
>>> x.bf = B.bf
>>> x.bf()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bf() missing 1 required positional argument: 'self'

Upvotes: 0

Views: 54

Answers (1)

rurouni88
rurouni88

Reputation: 1173

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 

or

# Use the existing instance of B and call bf
x.bf = b.bf

More information:

  1. A and B are your classes. They don't do anything until you instantiate them.
  2. x and b are your object instances. x is an instance of A, and b is an instance of B
  3. 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.

Upvotes: 1

Related Questions