Python Fundamentals: Classes
In Python, a class is a blueprint for creating objects. Classes encapsulate data and functions as methods.
a. Defining and creating an object of a class: Define a class using the 'class' keyword and then create its objects.
b. Initialisation with '__init__': The '__init__' method is a special method that is run when an object is instantiated.
c. Inheritance: Python classes can inherit properties and methods from other classes.
a. Defining and creating an object of a class: Define a class using the 'class' keyword and then create its objects.
Code
class Dog: def bark(self): return "Woof!" dog = Dog() print(dog.bark())
Output
Woof!
b. Initialisation with '__init__': The '__init__' method is a special method that is run when an object is instantiated.
Code
class Cat: def __init__(self, name): self.name = name def meow(self): return f"{self.name} says Meow!" cat = Cat("Whiskers") print(cat.meow())
Output
Whiskers says Meow!
c. Inheritance: Python classes can inherit properties and methods from other classes.
Code
class Animal: def speak(self): return "Some sound" class Cow(Animal): def speak(self): return "Moo" cow = Cow() print(cow.speak())
Output
Moo
d. In the above example the Cow class is overriding the speak method of the Animal class. If you want to also include the sound of the parent Animal class when the Cow speaks, you can call the parent method inside the speak method of the Cow class using the super() function.
Code
class Animal: def speak(self): return "Some sound" class Cow(Animal): def speak(self): return super().speak() + " and Moo" cow = Cow() print(cow.speak())
Output
Some sound and Moo