Important Python Mcqs

What will be the output of the following Python code?

class Name:
    def __init__(self, firstName, mi, lastName):
        self.firstName = firstName
        self.mi = mi
        self.lastName = lastName


firstName = "John"
name = Name(firstName, 'F', "Smith")
firstName = "Peter"
name.lastName = "Pan"
print(name.firstName, name.lastName)

a) Peter Pan

b) John Pan

c) Peter Smith

d) John Smith

Answer:

b) John Pan

Explanation:

In the constructor, firstname, mi, and lastname of the object are assigned as John, F, and Smith respectively. Then, we changed firstname to Peter outside the class so it did not change the name object. Finally, we used using the name.lastname = “Pan” which changed lastname of the object to Pan, thus answer is b.

Related MCQs
Aniket Malik

Aniket Malik

CERTIFIED TUTOR/TRAINER WITH 300+ REVIEWS

Facing difficulty with

this concept?