OOPs in Python MCQs Exercise II


Ques 1 OOPs


What is the output of the following Python Code?


class student:
    def __init__(self, roll_no,college):
        self.__roll_no=roll_no
        self.college=college
student1 = student(18345354332,"CSIT COE")
print(student1.__roll_no)

  a) 18345354332
  b) Error
  c) 18345354332
  d) None of these.


b is the correct option

The '__roll_no' attribute is a private variable because it is prefixed with double underscores (__). Private variables cannot be accessed directly outside the class.
Attempting to access 'student1.__roll_no' raises an AttributeError because Python uses name mangling for private variables.
To access the private variable, you would need to use the mangled name, e.g., 'student1._student__roll_no'.





Ques 2 OOPs


What is the output of the following Python Code?


class student:
    def __init__(self, roll_no,college):
        self.__roll_no=roll_no
        self.college=college
student1 = student(18345354332,"CSIT COE")
student1.branch="Information Technology"
student1.__branch="Information Technology"
print(student1.branch)

  a) Information Technology
  b) Error
  c) 18345354332
  d) None of these.


a is the correct option

The attribute branch is dynamically added to the student1 object with the value "Information Technology". This is a public attribute and can be accessed directly.
Another attribute, __branch, is also dynamically added. However, since it starts with double underscores, it is treated as a private variable (name mangling applies), and it is different from branch.
print(student1.branch) accesses the public branch attribute and outputs "Information Technology".