Junior — Middle
Can you give an example of a class definition in Python?
sobes.tech AI
Answer from AI
Example of defining a class in Python:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name} and I am {self.age} years old."
# Using the class
p = Person("Ivan", 30)
print(p.greet())
In this example, the Person class has a constructor __init__, which initializes the name and age, as well as a greet method that returns a greeting message.