Friday , September 20 2024

If the class’s constructor is declared as below, which one of the assignments is valid? class Class: def __init__(self): pass

Questions BankCategory: Python Essentials 2If the class’s constructor is declared as below, which one of the assignments is valid? class Class: def __init__(self): pass
If the class’s constructor is declared as below, which one of the assignments is valid?

class Class:
    def __init__(self):
        pass
  • object = Class
  • object = Class(object)
  • object = Class(self)
  • object = Class()

Explanation: The object = Class() assignment creates an object of class Class, and the __init__ method is automatically called when that object is created. The __init__ constructor has the obligatory parameter self, no attributes, and it does not do anything because a placeholder statement – pass – is executed.

The object = Class(object) assignment will result in a TypeError exception, because the __init__() method should take only one positional argument (self), not two (self and object).

The object = Class(self) assignment will result in a NameError exception, because the name self has not been defined anywhere.

The object = Class assignment declares the object variable and assigns Class to it, but it does not initialize an object of class Class.

More Questions: Python Essentials 2 – Module 3 Test