#3 – Object-Oriented Programming (OOP) Flashcards
(10 cards)
How do you define a basic class in Python?
Use the class
keyword.
class Dog: def \_\_init\_\_(self, name): self.name = name
How do you create an instance of a class?
Call the class like a function.
dog = Dog('Fido')
What is \_\_init\_\_
used for in a class?
It is a constructor method that runs when an object is created.
class Cat: def \_\_init\_\_(self, age): self.age = age
What does self
mean in a class?
self
refers to the instance of the class, allowing access to its attributes and methods.
How do you define a method inside a class?
Define a function with self
as the first parameter.
class A: def say_hi(self): print('Hi')
What is a dunder method in Python?
A ‘dunder’ method has double underscores (__) before and after. They’re special methods used by Python internally.
What is \_\_str\_\_
used for?
To define what should be returned when str(object)
or print(object)
is called.
def \_\_str\_\_(self): return f'My name is {self.name}'
What is \_\_repr\_\_
used for?
To return an official string representation for developers.
def \_\_repr\_\_(self): return f'Dog(name={self.name})'
What is inheritance in Python?
A class can inherit from another to reuse its code.
class Puppy(Dog): def bark(self): print('woof')
How do you call a method from the parent class?
Use super()
.
class Puppy(Dog): def \_\_init\_\_(self, name): super().\_\_init\_\_(name)