class Demo: def __init__(self): self.a = 1 self.__b = 1 def get(self): return self.__bobj = Demo()obj.a=45print(obj.a)
Question
Class Demo Implementation
class Demo:
def __init__(self):
self.a = 1
self.__b = 1
def get(self):
return self.__b
obj = Demo()
obj.a = 45
print(obj.a)
Solution
The code you've provided is written in Python. It defines a class Demo with an initializer method, a private attribute __b, a public attribute a, and a method get to return the value of the private attribute.
Here's a step-by-step explanation:
-
class Demo:This line is defining a new class namedDemo. -
def __init__(self):This line is defining the initializer method for the class. This method is called when an object of the class is created. -
self.a = 1This line is creating a public attributeafor the class and initializing it with the value1. -
self.__b = 1This line is creating a private attribute__bfor the class and initializing it with the value1. In Python, private attributes are denoted by double underscores before the attribute name. -
def get(self):This line is defining a methodgetfor the class. -
return self.__bThis line is returning the value of the private attribute__bwhen thegetmethod is called. -
obj = Demo()This line is creating an objectobjof the classDemo. -
obj.a=45This line is changing the value of the public attributeaof the objectobjto45. -
print(obj.a)This line is printing the value of the attributeaof the objectobj, which should output45.
Please note that the code you've provided is not properly formatted, which might cause syntax errors when running it. Here's the properly formatted version:
class Demo:
def __init__(self):
self.a = 1
self.__b = 1
def get(self):
return self.__b
obj = Demo()
obj.a=45
print(obj.a)
Similar Questions
class fruits: def __init__(self): self.price = 100 self.__bags = 5 def display(self): print(self.__bags)obj=fruits()obj.display()
what is the output of following python code? class myclass: def __init__(self,a): self.a = a print(self.a)o=myclass()
Which of the following is correct?class A: def __init__(self,name): self.name=namea1=A("john")a2=A("john")
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.
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.