OOP in Python
OOP in Python
Requests:
1. Defining a Class: 3. Instance Methods:
A class is defined using the class keyword, followed by the Methods are functions defined within a class that operate on the
class name (conventionally capitalized) and a colon. object's data. They also take self as their first parameter.
class MyClass: class Person:
x=5 def __init__(self, name, age):
self.name = name
p1 = MyClass() self.age = age
print(p1.x)
def myfunc(self):
print("Hello my name is " + self.name)
2. The __init__ Method (Constructor):
The __init__ method is a special method, often referred 4. Creating Objects (Instantiating the Class):
to as the constructor, which is automatically called when a To create an object from a class, you call the class name as if it were
new object (instance) of the class is created. It's used to a function, passing any required arguments for the __init__ method
initialize the object's attributes. The first parameter, self,
refers to the instance itself. p1 = Person("John", 36)
Create a class named Person, use the __init__() method to
assign values for name and age: 5. Accessing Attributes and Calling Methods:
class Person: You can access an object's attributes and call its methods using the
def __init__(self, name, dot (.) operator. print(p1.name)
age): . print(p1.age)
self.name = name
Requests:
Class: A Colleton of functions and attributes, attached to a specific
name, which represents an abstract concept.
Attribute: A named piece of data (i.e. variable associated with a class.
Object: A single concrete instance generated from a class
Instances of Classes: Classes can be viewed as factories or templates
for genera ng new object instances. Each object instance takes on the
proper es of the class from which it was created.
class Person:
def __init__(self, name, age):
self.name = name # Initialize the 'name' attribute
self.age = age # Initialize the 'age' attribute
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")