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()
Question
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()
Solution
The output of the given Python code will be "5".
Here's the step by step explanation:
-
A class named 'fruits' is defined with two attributes: 'price' and '__bags'. The 'price' attribute is public, and '__bags' is private due to the double underscore prefix.
-
The class also has a method named 'display' which prints the value of the private attribute '__bags'.
-
An object 'obj' of the class 'fruits' is created.
-
The 'display' method of the 'obj' object is called, which prints the value of '__bags'. Since '__bags' was initialized with the value 5 in the constructor, the output will be "5".
Similar Questions
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)
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 fruits: def __init__(self): self.price = 100 self.__bags = 5 def display(self): print(self.__bags)obj=fruits()obj.display() The program has an error because display() is trying to print a private class memberThe program runs fine but nothing is printedThe program runs fine and 5 is printed The program has an error because display() can’t be accessed
What is the output of the following code? python class A: def display(self): print("Class A") class B(A): def display(self): print("Class B") class C(A): def display(self): print("Class C") obj = B() obj.display() obj = C() obj.display()
What will be the output of the following code?class MyClass: def __init__(self, value=5): self.value = valueobj1 = MyClass()obj2 = MyClass(10)print(obj1.value, obj2.value)
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.