Here’s an example of a Python class that represents a rectangle:
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
# Create a Rectangle object
rect = Rectangle(10, 20)
# Print the area and perimeter of the rectangle
print("Area:", rect.area())
print("Perimeter:", rect.perimeter())
In this example, the Rectangle
class has two attributes width
and height
which are passed as arguments to the __init__
method when a new Rectangle
object is created. The class also has two methods area
and perimeter
that return the area and perimeter of the rectangle, respectively.Regenerate response
Here’s another example of a Python class that represents a dog:
class Dog:
def __init__(self, name, breed, age):
self.name = name
self.breed = breed
self.age = age
def bark(self):
print("Woof!")
def info(self):
print("Name:", self.name)
print("Breed:", self.breed)
print("Age:", self.age)
# Create a Dog object
dog = Dog("Buddy", "Labrador", 5)
# Print the dog's information and make it bark
dog.info()
dog.bark()
In this example, the Dog
class has three attributes name
, breed
, and age
which are passed as arguments to the __init__
method when a new Dog
object is created. The class also has two methods bark
and info
that make the dog bark and print its information, respectively.