The class
keyword in Python is used to define a class, which is a blueprint for creating objects. A class encapsulates data and functionality together.
class Dog:
"""
A simple class representing a dog.
"""
# Class attribute
species = "Canis familiaris"
# Instance method
def bark(self):
return "Woof!"
# Create an instance of the Dog class
my_dog = Dog()
# Access class attribute
print(my_dog.species) # Output: Canis familiaris
# Call instance method
print(my_dog.bark()) # Output: Woof!
In Python, self
is a reference to the instance of the class itself. It is used to access attributes and methods of the class in object-oriented programming.
class Dog:
"""
A simple class representing a dog.
"""
# Initializer / Instance attributes
def __init__(self, name, age):
self.name = name
self.age = age
# Instance method
def bark(self):
return f"{self.name} is barking!"
# Instance method
def get_age(self):
return f"{self.name} is {self.age} years old."
# Create an instance of the Dog class
my_dog = Dog("Buddy", 3)
# Access instance attributes
print(my_dog.name) # Output: Buddy
print(my_dog.age) # Output: 3
# Call instance methods
print(my_dog.bark()) # Output: Buddy is barking!
print(my_dog.get_age()) # Output: Buddy is 3 years old.
The init method in Python is a special method called a constructor. It is automatically called when a new instance of a class is created. The init method initializes the instance's attributes.
class Dog:
"""
A simple class representing a dog.
"""
# Initializer / Instance attributes
def __init__(self, name, age):
self.name = name
self.age = age
# Instance method
def bark(self):
return f"{self.name} is barking!"
# Instance method
def get_age(self):
return f"{self.name} is {self.age} years old."
# Create an instance of the Dog class
my_dog = Dog("Buddy", 3)
# Access instance attributes
print(my_dog.name) # Output: Buddy
print(my_dog.age) # Output: 3
# Call instance methods
print(my_dog.bark()) # Output: Buddy is barking!
print(my_dog.get_age()) # Output: Buddy is 3 years old.
Inheritance in Python is a mechanism that allows a class (called the child or subclass) to inherit attributes and methods from another class (called the parent or superclass). This promotes code reuse and can create a hierarchical relationship between classes.
# Define the parent class
class Animal:
"""
A simple class representing an animal.
"""
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound."
# Define the child class
class Dog(Animal):
"""
A class representing a dog, inheriting from Animal.
"""
def __init__(self, name, age):
# Call the constructor of the parent class
super().__init__(name)
self.age = age
def speak(self):
return f"{self.name} says Woof!"
# Create an instance of the Dog class
my_dog = Dog("Buddy", 3)
# Access attributes and methods
print(my_dog.name) # Output: Buddy
print(my_dog.age) # Output: 3
print(my_dog.speak()) # Output: Buddy says Woof!