What will be the output of the following Python code?class Student: def __init__(self,id): self.id = id print(self.id, end=" ") std=Student(5)std.id=7print(std.id, end=" ")
Question
What will be the output of the following Python code?class Student: def init(self,id): self.id = id print(self.id, end=" ") std=Student(5)std.id=7print(std.id, end=" ")
Solution
The output of the Python code will be:
5 7
Here's the step-by-step explanation:
-
The class
Studentis defined with an__init__method. This method is a special method in Python classes which is automatically called when an object of the class is created. It is used to initialize the attributes of the class. -
In the
__init__method,self.id = idsets theidattribute of the class to the value passed when the object is created. -
print(self.id, end=" ")prints theidattribute of the class and a space. Theend=" "argument in theprintfunction changes the default newline character at the end of the output to a space. -
std=Student(5)creates an object of theStudentclass withid5. This will print5. -
std.id=7changes theidattribute of thestdobject to 7. -
print(std.id, end=" ")prints theidattribute of thestdobject and a space. This will print7.
So, the output of the code is 5 7 .
Similar Questions
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)
What will be the output of the following Python code? class student: def __init__(self): self.marks = 97 self.__cgpa = 8.7 def display(self): print(self.marks)obj=student()print(obj._student__cgpa)
what is the output of following python code? class myclass: def __init__(self,a): self.a = a print(self.a)o=myclass("Welcome")
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)
What will be the output of the following Python code?class Demo: def __init__(self): self.a = 1 self.__b = 1 def get(self): return self.__bobj = Demo()obj.a=45print(obj.a)
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.