Knowee
Questions
Features
Study Tools

What will be the output of the following Python code? class student: def __init__(self): self.marks = 97 self.__cgpa = 8.7 def display(self): print(self.marks)obj=student()print(obj._student__cgpa)

Question

What will be the output of the following Python code? class student: def init(self): self.marks = 97 self.__cgpa = 8.7 def display(self): print(self.marks)obj=student()print(obj._student__cgpa)

🧐 Not the exact question you are looking for?Go ask a question

Solution

The output of the Python code will be 8.7.

Here's the step by step explanation:

  1. A class named 'student' is defined with two attributes: 'marks' and '__cgpa'. The 'marks' attribute is public, while '__cgpa' is private due to the double underscore prefix.

  2. The class also has a method named 'display' which prints the value of the 'marks' attribute.

  3. An object 'obj' of the class 'student' is created.

  4. The print statement is trying to access the private attribute '__cgpa' of the 'student' class. In Python, private attributes are not directly accessible. However, they can be accessed indirectly by using '_classname__attributename'.

  5. So, 'obj._student__cgpa' is used to access the private attribute '__cgpa' of the 'student' class.

  6. Therefore, the output of the code will be 8.7, which is the value of the '__cgpa' attribute.

This problem has been solved

Similar Questions

What will be the output of the following Python code? class student: def __init__(self): self.marks = 97 self.__cgpa = 8.7 def display(self): print(self.marks)obj=student()print(obj._student__cgpa) The program runs fine and 8.7 is printed Error because private class members can’t be accessed Error because the proper syntax for name mangling hasn’t been implemented The program runs fine but nothing is printedClear ResponseSave & Next

What will be the output of the following Python code?class fruits: def __init__(self): self.price = 100 self.__bags = 5 def display(self): print(self.__bags)obj=fruits()obj.display()

What will be the output of the following Python code?class Demo: def __init__(self): self.a = 1 self.__b = 1  def display(self): return self.__b obj = Demo()print(obj.__b)

What will be the output of below Python code?class Student:    def __init__(self,name,id):        self.name=name        self.id=id        print(self.id)std=Student("Simon",1)std.id=2print(std.id)

What will be the output of the following Python code?class A: def __init__(self): self.__i = 1 self.j = 5  def display(self): print(self.__i, self.j)class B(A): def __init__(self): super().__init__() self.__i = 2 self.j = 7 c = B()c.display()2 71 51 72 5

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.