Junior
What are the two ways to create a class in Python?
sobes.tech AI
Answer from AI
- Using the
classkeyword. This is the most common and recommended way.
# Defining a class using the class keyword
class MyClass:
def __init__(self, value):
self.value = value
def display(self):
print(f"Value: {self.value}")
# Creating an instance of the class
obj = MyClass(10)
obj.display()
- Using the
type()function. In Python, classes are first-class objects, andtype()is a function that can create classes dynamically.
# Defining a class using the type() function
def init_func(self, value):
self.value = value
def display_func(self):
print(f"Value: {self.value}")
MyClassDynamic = type(
"MyClassDynamic", # Class name
(), # Tuple of base classes (empty if no inheritance)
{ # Dictionary of attributes and methods (class namespace)
"__init__": init_func,
"display": display_func
}
)
# Creating an instance of the class created with type()
obj_dynamic = MyClassDynamic(20)
obj_dynamic.display()
Comparison table:
| Creation method | Advantages | Disadvantages |
|---|---|---|
class |
Readability, clarity, IDE support | Less flexible for dynamic creation |
type() |
Flexibility, ability to create classes dynamically | Less readable, less common |