Junior — Middle
How is the class structure implemented in Python?
sobes.tech AI
Answer from AI
In Python, the class structure is implemented using the class keyword. A class is a template for creating objects (instances), combining data (attributes) and behavior (methods).
A class in Python is a first-class object and can contain:
- Class attributes (shared among all instances)
- Instance attributes (unique to each object)
- Methods (functions defined within the class)
Example of class definition:
class Person:
species = "Homo sapiens" # class attribute
def __init__(self, name, age):
self.name = name # instance attribute
self.age = age
def greet(self):
print(f"Hello, my name is {self.name}.")
# Creating an instance
p = Person("Ivan", 30)
p.greet() # Outputs: Hello, my name is Ivan.
Python classes support inheritance, polymorphism, and encapsulation, allowing the construction of complex object hierarchies.