LinkedIn Python Skill Assessment Quiz Answers

What is the correct syntax for defining an __init__() method that sets instance-specific attributes upon creation of a new class instance?

Latest Update on 25th January, 2022 by Certification Course Answers

What is the correct syntax for defining an __init__() method that sets instance-specific attributes upon creation of a new class instance?

def __init__(self, attr1, attr2):
    attr1 = attr1
    attr2 = attr2
def __init__(attr1, attr2):
    attr1 = attr1
    attr2 = attr2
def __init__(self, attr1, attr2):
    self.attr1 = attr1
    self.attr2 = attr2
def __init__(attr1, attr2):
    self.attr1 = attr1
    self.attr2 = attr2

Correct Answer:

def __init__(self, attr1, attr2):
    self.attr1 = attr1
    self.attr2 = attr2

Explanation: When instantiating a new object from a given class, the __init__() method will take both attr1 and attr2, and set its values to their corresponding object attribute, that’s why the need of using self.attr1 = attr1 instead of attr1 = attr1.

Latest Updates

No posts found in this category.