OOP is a programming paradigm based on the concept of "objects," which can contain data (attributes) and code (methods) that operate on that data.
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print("Woof!")
This defines a class called Dog
. The __init__
method is a special method (constructor) that is called when a new object (instance) of the class is created.
my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.name) # Output: Buddy
print(my_dog.breed) # Output: Golden Retriever
my_dog.bark() # Output: Woof!
class Dog:
def __init__(self, name, breed, age):
self.name = name
self.breed = breed
self.age = age
def bark(self):
print("Woof!")
def get_age(self):
return self.age
my_dog2 = Dog("Lucy", "Labrador", 3)
print(my_dog2.get_age())
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
rect = Rectangle(5, 10)
print(rect.area()) # Output: 50
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * (self.radius * self.radius)
circle = Circle(7)
print(circle.area())
name
, breed
).