Classes and Objects in Python (Part-9)

Creating a Class and Object in Python

1. Create Class

  • Definition:
    • A class is a blueprint for creating objects.
    • It defines a set of attributes and methods that the created objects will have.

Example:

class MyClass:
    x = 5
  • Explanation:
    • The keyword class is used to define a class.
    • MyClass is the name of the class.
    • x is a class attribute with a value of 5.

2. Create Object

  • Definition:
    • An object is an instance of a class.
    • It can use the attributes and methods defined in the class.

Example:

p1 = MyClass()
print(p1.x)  # Output: 5
  • Explanation:
    • p1 is an object of MyClass.
    • MyClass() creates an instance of the class.
    • p1.x accesses the attribute x of the class, which is 5.

Key Points

  1. Class Definition:
    • A class is defined using the class keyword.
    • It contains attributes and methods that define the properties and behaviors of the objects created from the class.
  2. Creating an Object:
    • An object is created by calling the class name followed by parentheses.
    • The object can access the attributes and methods defined in the class.
  3. Attributes and Methods:
    • Attributes are variables that belong to the class.
    • Methods are functions defined inside the class that describe the behaviors of the objects.

Example with Methods

Example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

p1 = Person("John", 36)
p1.greet()  # Output: Hello, my name is John and I am 36 years old.
  • Explanation:
    • __init__ is a special method called a constructor that initializes the object’s attributes.
    • self refers to the instance of the class.
    • name and age are instance attributes.
    • greet is a method that prints a greeting message.

Summary

  • Creating a Class: Use the class keyword to define a class with attributes and methods.
  • Creating an Object: Instantiate the class to create an object that can use the class attributes and methods.
  • Attributes and Methods: Define the properties and behaviors of the objects through attributes and methods.

if we create a = ‘abcd’

check the by print(type(a))

it will return class as string

Basic Class and Object

  1. Creating a Class and an Object
class MyClass:
    x = 5

# Create an object
p1 = MyClass()
print(p1.x)
# Output: 5

Class with Methods

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

# Create an object
p1 = Person("John", 36)
p1.greet()
# Output: Hello, my name is John and I am 36 years old.

Advanced Examples

  1. Class with Private Variables
class Person:
    def __init__(self, name, age):
        self.__name = name  # Private variable
        self.__age = age    # Private variable

    def greet(self):
        print(f"Hello, my name is {self.__name} and I am {self.__age} years old.")

# Create an object
p1 = Person("John", 36)
p1.greet()
# Output: Hello, my name is John and I am 36 years old.

Class Inheritance

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

class Student(Person):
    def __init__(self, name, age, student_id):
        super().__init__(name, age)
        self.student_id = student_id

    def display_id(self):
        print(f"My student ID is {self.student_id}")

# Create an object
s1 = Student("Alice", 20, "S12345")
s1.greet()
s1.display_id()
# Output:
# Hello, my name is Alice and I am 20 years old.
# My student ID is S12345

Class with Class Variables

class Employee:
    company_name = "ABC Corp"  # Class variable

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def display_employee(self):
        print(f"Name: {self.name}, Salary: {self.salary}, Company: {Employee.company_name}")

# Create objects
e1 = Employee("John", 50000)
e2 = Employee("Alice", 60000)

e1.display_employee()
e2.display_employee()
# Output:
# Name: John, Salary: 50000, Company: ABC Corp
# Name: Alice, Salary: 60000, Company: ABC Corp

Class with Static Methods

class MathOperations:
    @staticmethod
    def add(a, b):
        return a + b

# Call static method without creating an object
result = MathOperations.add(5, 3)
print(result)
# Output: 8

Related Posts

Package your Python code as Wheel File (Part-20)

Package your Python code as Wheel File If you want to share code with others or create libraries for your code so other can use your code….

Read More

map() function in Python (Part-19)

Using map() Function in Python The map() function in Python is used to apply a function to all the items in an input list. Here are some…

Read More

User Input | input() function |File Handling| open() function in Python (Part-18)

Using input() in Python 3.6 and later When you run this code, it will prompt you to enter a username and then print the entered username. Using…

Read More

Try…Except in Python | Exception handling in Python (part-17)

Exception Handling When an error occurs, or exception as we call it, Python will normally stop and generate an error message. These exceptions can be handled using…

Read More

PIP in Python (Part-16)

What is PIP? PIP is a package manager for Python. It allows you to install and manage additional libraries and dependencies that are not included in the…

Read More

JSON in Python (Part-15)

JSON in Python JSON (JavaScript Object Notation) is a lightweight data interchange format that’s easy for humans to read and write, and easy for machines to parse…

Read More
guest
0 Comments
Oldest
Newest Most Voted
0
Would love your thoughts, please comment.x
()
x