Python / Core Python Fundamentals Interview Questions
How do you define a class in Python, and what is the role of __init__?
A class is a blueprint for objects. Define it with the class keyword. The special method __init__ (the constructor) is called automatically when you create an instance and is where you set up the object's initial state by assigning to self.attribute.
class BankAccount:
interest_rate = 0.03 # class attribute — shared by all instances
def __init__(self, owner, balance=0):
self.owner = owner # instance attributes
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError('Deposit amount must be positive')
self.balance += amount
def __repr__(self):
return f'BankAccount({self.owner!r}, balance={self.balance})'
acc = BankAccount('Alice', 1000)
acc.deposit(500)
print(acc) # BankAccount('Alice', balance=1500)
print(acc.interest_rate) # 0.03self is a reference to the current instance; it is not a keyword but the universal convention. Every instance method receives it as the first parameter. Class attributes are defined directly in the class body and shared across all instances; instance attributes are set with self.attr = value inside methods and belong to each object individually.
Important dunder methods to know: __str__ (readable string for end users, called by print), __repr__ (unambiguous string for developers, called in the REPL), __len__, __eq__, __lt__, and __enter__/__exit__ for context managers.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
