Which of the following is the correct way to define a simple class in Python?
easy📝 Syntax Q12 of 15
Python - Object-Oriented Programming Foundations
Which of the following is the correct way to define a simple class in Python?
Aclass Car:
def __init__(self, color):
self.color = color
Bdef Car:
color = 'red'
Cclass Car():
color = 'red'
def __init__(self):
pass
Dclass Car:
def __start__(self):
print('Start')
Step-by-Step Solution
Solution:
Step 1: Check class syntax
class Car:
def __init__(self, color):
self.color = color correctly defines a class with an __init__ method and assigns an instance variable.
Step 2: Identify syntax errors in other options
def Car:
color = 'red' uses def instead of class. class Car():
color = 'red'
def __init__(self):
pass lacks proper __init__ usage for color. class Car:
def __start__(self):
print('Start') uses __start__ which is not a special method.
Final Answer:
class Car:\n def __init__(self, color):\n self.color = color -> Option A
Quick Check:
Correct class with __init__ = B [OK]
Quick Trick:Class needs __init__ method for attributes [OK]
Common Mistakes:
Using def instead of class to define a class
Missing self parameter in methods
Using wrong special method names
Master "Object-Oriented Programming Foundations" in Python
9 interactive learning modes - each teaches the same concept differently