Class Definition: To define a class, you use the class
keyword. The basic syntax is as follows:
class ClassName:
# Class body
Example:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says Woof!")
Attributes: Attributes are variables that store data related to the class. They are defined within the class and are accessed using the self
keyword.
Methods: Methods are functions defined within a class. They operate on the attributes of the class and are defined using the def
keyword.
Inheritance: Classes can inherit attributes and methods from other classes. The derived class is called a subclass, and the class from which it inherits is called the superclass.
class Animal:
def __init__(self, species):
self.species = species
class Dog(Animal):
def __init__(self, name, age):
super().__init__("Dog")
self.name = name
self.age = age