What are Objects in Python
In Python, everything is an object. This means that in Python, you can use objects to represent real-world entities, such as a person or a bank account.
Classes
In Python, a class is a template that is used to create objects. A class defines the attributes and behaviors of an object.
To create a class in Python, you use the class
keyword, followed by the name of the class, and the class definition (enclosed in curly braces).
Here is an example of a class in Python:
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.")
In the example above, the Person
class has two attributes: name
and age
. It also has a greet
method that prints a greeting message.
The __init__
method is a special method in Python that is used to initialize an object. It is called when the object is created.
Instances
To create an object (also called an instance) from a class, you use the class name followed by the arguments for the __init__
method (enclosed in parentheses).
Here is an example of how to create an object from the Person
class:
p1 = Person("John", 30)
To access the attributes and behaviors of an object, you use the .
dot notation.
Here is an example of how to access the attributes and behaviors of the p1
object:
print(p1.name) # Output: "John"
print(p1.age) # Output: 30
p1.greet() # Output: "Hello, my name is John and I am 30 years old."
You can also update the attributes of an object by simply reassigning them.
p1.name = "Jane"
p1.age = 25
print(p1.name) # Output: "Jane"
print(p1.age) # Output: 25
p1.greet() # Output: "Hello, my name is Jane and I am 25 years old."
Inheritance
In Python, inheritance is a way to create a new class that is a modified version of an existing class. The new class is called the subclass, and the existing class is the superclass.
The subclass can have additional attributes and behaviors, as well as override or extend the attributes and behaviors of the superclass.
To create a subclass in Python, you use the class
keyword, followed by the name of the subclass, the (SuperClass)
syntax, and the class definition (enclosed in curly braces).
Here is an example of a subclass in Python:
class Animal:
def __init__(self, species):
self.species = species
def make_sound(self):
print("Some generic animal sound")
class Dog(Animal):
def __init__(self, breed):
super().__init__("Dog")
self.breed = breed
def make_sound(self):
print("Bark")
In the example above, the Dog
class is a subclass of the Animal
class. It has an additional attribute: breed
. It also has a modified make_sound
method that overrides the make_sound
method of the Animal
class.
To call the superclass method from the subclass, you can use the super()
function.
In the example above, the __init__
method of the Dog
class calls the __init__
method of the Animal
class using the super()
function. This allows the Dog
class to initialize the species
attribute inherited from the Animal
class.
dog1 = Dog("Labrador")
print(dog1.species) # Output: "Dog"
print(dog1.breed) # Output: "Labrador"
dog1.make_sound() # Output: "Bark"
In Python, you can also use multiple inheritance, where a subclass can inherit from multiple superclasses.
Here is an example of multiple inheritance in Python:
class A:
def do_something(self):
print("Doing something in class A")
class B:
def do_something(self):
print("Doing something in class B")
class C(A, B):
pass
c = C()
c.do_something() # Output: "Doing something in class A"
In the example above, the C
class inherits from both the A
and B
classes. When the do_something
method is called on the c
object, the implementation from the A
class is used because it appears first in the inheritance list.
Polymorphism
Polymorphism is the ability of a class to have different forms. In Python, you can use polymorphism to create methods with the same name in different classes, but with different implementations.
Here is an example of polymorphism in Python:
class Animal:
def make_sound(self):
print("Some generic animal sound")
class Dog(Animal):
def make_sound(self):
print("Bark")
class Cat(Animal):
def make_sound(self):
print("Meow")
animals = [Animal(), Dog(), Cat()]
for animal in animals:
animal.make_sound()
# Output:
# Some generic animal sound
# Bark
# Meow
In the example above, the Animal
, Dog
, and Cat
classes all have a make_sound
method, but with different implementations.
When the make_sound
method is called on the objects in the animals
list, the correct implementation is called based on the object's class.
This is an example of polymorphism because the make_sound
method has different forms (implementations) depending on the object's class.
Special Methods
In Python, you can use special methods to define the behavior of objects when they are used in certain ways.
Here are some examples of special methods in Python:
__str__
: This method is called when the object is passed to thestr()
function. It should return a string representation of the object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Person(name={self.name}, age={self.age})"
p = Person("John", 30)
print(str(p)) # Output: "Person(name=John, age=30)"
__len__
: This method is called when the object is passed to thelen()
function. It should return the length of the object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __len__(self):
return self.age
p = Person("John", 30)
print(len(p)) # Output: 30
__add__
: This method is called when the object is used in an addition operation. It should return the result of the addition.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2
print(v3.x) # Output: 4
print(v3.y) # Output: 6
These are just a few examples of special methods in Python. There are many other special methods that you can use.
More content at PlainEnglish.io.
Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.
Build awareness and adoption for your tech startup with Circuit.