class fruits: def __init__(self): self.price = 100 self.__bags = 5 def display(self): print(self.__bags)obj=fruits()obj.display()
Question
Code Example
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 = 100
This line is initializing an attributeprice
of the classfruits
and setting its value to 100. -
self.__bags = 5
This line is initializing a private attribute__bags
of the classfruits
and 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 methoddisplay
for the classfruits
. -
print(self.__bags)
This line is inside thedisplay
method and it prints the value of the private attribute__bags
. -
obj=fruits()
This line is creating an objectobj
of the classfruits
. This will call the__init__
method and initialize the attributesprice
and__bags
. -
obj.display()
This line is calling thedisplay
method 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
class Demo: def __init__(self): self.a = 1 self.__b = 1 def get(self): return self.__bobj = Demo()obj.a=45print(obj.a)
what is the output of following python code? class myclass: def __init__(self,a): self.a = a print(self.a)o=myclass()
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)
class Dog:def __init__(self):# missing line hered = Dog()print(d.age)Fill in the missing line of code, so that the output for this code is 5.
The listing of attributes and methods of user-defined class in Python is generated by
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.