Data Science · मराठी आवृत्ती · Python basics
P11.2 Python Class मध्ये Methods कशा जोडायच्या?
हे का शिकायचं?
Account मध्ये पैसे भरणं-काढणं ही कामं account सोबतच असावीत.
हे काय आहे?
Method म्हणजे class आतलं function. पहिला argument self असतो आणि त्याने object ची values बदलता येतात.
कसं करायचं?
Step 1. Class आत def method(self, …) लिहा.
Step 2. object.method() ने call करा.
उदाहरणं: copy करा आणि चालवा
उदाहरण A: Deposit आणि withdraw
हा code चालवा:
class Account:
def __init__(self, holder, balance=0):
self.holder = holder
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
print("Not enough money")
else:
self.balance -= amount
a = Account("Emma", 500)
a.deposit(200)
a.withdraw(1000)
a.withdraw(300)
print(a.balance)
तुम्हाला दिसणारा output:
Not enough money
400
याचा अर्थ: Methods ने balance बदलला. जास्त पैसे काढायचा प्रयत्न नाकारला.
उदाहरण B: Text return करणारी method
हा code चालवा:
class Order:
def __init__(self, order_id, amount, currency="₹"):
self.order_id = order_id
self.amount = amount
self.currency = currency
def summary(self):
return f"{self.order_id}: {self.currency}{self.amount:,.2f}"
print(Order("BLK-1001", 1450).summary())
print(Order("NY-77", 89.5, "$").summary())
तुम्हाला दिसणारा output:
BLK-1001: ₹1,450.00
NY-77: $89.50
याचा अर्थ: Method ने object ची माहिती छान text मध्ये दिली.