Class object simple
- Get link
- X
- Other Apps
Python class and objcet with methods simple example
Sure. Here is a very simple Python example of Class, Object, and Methods:
Example: Student Class
class Student: # Method def display(self): print("Hello, I am a student") # Creating Object s1 = Student() # Calling Method s1.display()
Output:
Hello, I am a student
Understanding
Class → A blueprint/template.
class Student:Object → An instance of a class.
s1 = Student()Method → A function defined inside a class.
def display(self): print("Hello, I am a student")Calling method
s1.display()
Example with Data
class Student: def __init__(self, name, age): self.name = name self.age = age def display(self): print("Name:", self.name) print("Age:", self.age) # Objects s1 = Student("Rahul", 20) s2 = Student("Priya", 21) # Calling method s1.display() s2.display()
Output:
Name: Rahul Age: 20 Name: Priya Age: 21
Here, __init__() is a constructor, and self refers to the current object.
- Get link
- X
- Other Apps
Comments
Post a Comment