Knowee
Questions
Features
Study Tools

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()
🧐 Not the exact question you are looking for?Go ask a question

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:

  1. class fruits: This line is defining a class named fruits.

  2. 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.

  3. self.price = 100 This line is initializing an attribute price of the class fruits and setting its value to 100.

  4. self.__bags = 5 This line is initializing a private attribute __bags of the class fruits 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.

  5. def display(self): This line is defining a method display for the class fruits.

  6. print(self.__bags) This line is inside the display method and it prints the value of the private attribute __bags.

  7. obj=fruits() This line is creating an object obj of the class fruits. This will call the __init__ method and initialize the attributes price and __bags.

  8. obj.display() This line is calling the display method of the object obj. This will print the value of __bags, which is 5.

So, when you run this code, it will print 5 as output.

This problem has been solved

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

1/1

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.