Classes and Objects in Python
Classes and Objects in Python
1. What is a Class?
A class is a blueprint for creating objects. It defines a set of attributes and methods that the
created objects will have. Classes help in organizing code and managing data effectively.
Syntax:
class ClassName:
# Attributes (variables)
# Methods (functions)
Example:
class Car:
# Attributes
brand = "Toyota"
# Method
def start_engine(self):
print("Engine started!")
2. Creating Objects
An object (or instance) is a specific realization of a class. You create an object by calling the
class name followed by parentheses.
Example:
3. Attributes
Attributes are variables that belong to the class. They can hold data relevant to the object.
● Instance Attributes: These are unique to each instance and are defined in the
__init__ method.
● Class Attributes: These are shared among all instances of a class.
Example of Instance Attributes:
class Dog:
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age # Instance attribute
my_dog = Dog("Buddy", 3)
print("Dog's Name:", my_dog.name) # Output: Dog's Name: Buddy
print("Dog's Age:", my_dog.age) # Output: Dog's Age: 3
class Dog:
species = "Canis familiaris" # Class attribute
my_dog = Dog()
print("Dog Species:", my_dog.species) # Output: Dog Species: Canis
familiaris
4. Methods
Methods are functions defined within a class that describe the behaviors of an object. They take
self as the first parameter, which refers to the instance calling the method.
Example:
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(self.name + " says Woof!")
my_dog = Dog("Charlie")
my_dog.bark() # Output: Charlie says Woof!
Example:
class Dog:
species = "Canis familiaris"
@classmethod
def get_species(cls):
return cls.species
● Static Methods: These methods do not access or modify the class or instance state.
They are defined using the @staticmethod decorator.
Example:
class Dog:
@staticmethod
def bark():
print("Woof!")
Example:
class Dog:
def __init__(self, name):
self.name = name
my_dog = Dog("Max")
my_dog.greet("Hello") # Output: Hello, my name is Max!
class Dog:
def __init__(self, age):
self.age = age # Instance variable
def print_info(self):
local_var = "Local Dog Name" # Local variable
print("Dog Name: " + name + ", Age: " + str(self.age)) #
Accessing global variable
print("Local Variable: " + local_var)
my_dog = Dog(5)
my_dog.print_info()
Conclusion
Classes and objects are fundamental building blocks in Python programming. They allow for the
organization of code into manageable sections, promote reusability, and encapsulate data for
better structure and integrity.