class fruits: def __init__(self): self.price = 100 self.__bags = 5 def display(self): print(self.__bags)obj=fruits()obj.display()
Question
class fruits: def init(self): self.price = 100 self.__bags = 5 def display(self): print(self.__bags)obj=fruits()obj.display()
Solution
The given code is written in Python and it defines a class named fruits. Here's a step-by-step explanation of the code:
-
class fruits:This line is defining a class namedfruits. -
def __init__(self):This line is defining the constructor method for the class. The__init__method is called when an object is created from the class and it allows the class to initialize the attributes of the class. -
self.price = 100This line is initializing an attributepriceof the classfruitsand setting its value to 100. -
self.__bags = 5This line is initializing a private attribute__bagsof the classfruitsand setting its value to 5. The double underscore before the attribute name makes it private, meaning it can only be accessed within the class it is defined. -
def display(self):This line is defining a methoddisplayfor the classfruits. -
print(self.__bags)This line is inside thedisplaymethod and it prints the value of the private attribute__bags. -
obj=fruits()This line is creating an objectobjof the classfruits. This will call the__init__method and initialize the attributespriceand__bags. -
obj.display()This line is calling thedisplaymethod of the objectobj. This will print the value of__bags, which is 5.
So, when you run this code, it will print 5 as output.
Similar Questions
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 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
class Demo: def __init__(self): self.a = 1 self.__b = 1 def get(self): return self.__bobj = Demo()obj.a=45print(obj.a)
Choose the Correct AnswerWhat is the output of the following code?class test: def __init__(self,a): self.a=a def display(self): print(self.a)obj=test()obj.display()OptionsaError as argument is required while creating the objectIt will Executes but display nothingNone of the Above
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.