How does python support object-oriented programming? Flashcards

(3 cards)

1
Q

Key Elements of OOP in Python

A

Inheritance: Helps achieve code reusability.

Encapsulation: Data hiding possible through name mangling and property setters.

Polymorphism: Achieved through method overloading, overriding, and duck typing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Terminology

A

Class: Blueprint for creating objects.

Object: Instance of a class.

Method: Function defined within a class.

Attribute: Data bound to an object or class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Code Example: OOP in Python

A
class Shape:
    def \_\_init\_\_(self, name):
        self.name = name

    def describe(self):
        return f"I am a {self.name}."

class Circle(Shape):
    def \_\_init\_\_(self, radius):
        super().\_\_init\_\_("circle")
        self.radius = radius

    def area(self):
        return 3.14 * self.radius * self.radius

class Square(Shape):
    def \_\_init\_\_(self, side_length):
        super().\_\_init\_\_("square")
        self.side_length = side_length

    def area(self):
        return self.side_length ** 2

Create instances and invoke methods
circle = Circle(5)
print(circle.describe())
print("Area of the circle:", circle.area())

square = Square(4)
print(square.describe())
print("Area of the square:", square.area())
How well did you know this?
1
Not at all
2
3
4
5
Perfectly