మాడ్యూల్ పాఠాలు (1/4)
తరగతులు మరియు సందర్భాలు
తరగతి అనేది డేటా (గుణాలు) ఉన్న వస్తువులను సృష్టించడానికి ఒక బ్లూప్రింట్. మరియు ప్రవర్తన (పద్ధతులు). ఉదాహరణ అనేది దీని నుండి సృష్టించబడిన కాంక్రీట్ వస్తువు తరగతి.
కనిష్ట వాక్యనిర్మాణం
class Cane:
def __init__(self, nome, eta):
self.nome = nome
self.eta = eta
def abbaia(self):
return f"{self.nome} dice WOOF!"
# creazione di istanze
fido = Cane("Fido", 3)
luna = Cane("Luna", 5)
fido.nome # 'Fido'
fido.abbaia() # 'Fido dice WOOF!'__init__: "కన్స్ట్రక్టర్"
మీరు సృష్టించినప్పుడు __init__ పద్ధతిని ఆటోమేటిక్గా అంటారు
ఉదాహరణ (Cane("Fido", 3)). ఇది లక్షణాలను ప్రారంభించేందుకు ఉపయోగించబడుతుంది.
సాంకేతికంగా ఇది కన్స్ట్రక్టర్ కాదు (ఆబ్జెక్ట్ ఇప్పటికే సృష్టించబడింది
__new__), కానీ మీరు ప్రారంభ స్థితిని సెట్ చేసిన ప్రదేశం ఇది.
self: మొదటి పరామితి
self అనేది పద్ధతిని పిలిచిన సందర్భానికి సూచన. ఇది ఒక
కన్వెన్షన్ (కీవర్డ్ కాదు) మరియు ఇది ఎల్లప్పుడూ మొదటి పరామితి ఉదాహరణ
పద్ధతులు.
fido.abbaia()
# equivalente a Cane.abbaia(fido)
# Python passa fido come self automaticamenteఉదాహరణ vs తరగతి లక్షణాలు
class Cane:
specie = "Canis familiaris" # attributo di CLASSE (condiviso)
def __init__(self, nome):
self.nome = nome # attributo di ISTANZA (per ognuno)
fido = Cane("Fido")
luna = Cane("Luna")
fido.nome # 'Fido' (istanza)
luna.nome # 'Luna' (istanza)
fido.specie # 'Canis familiaris' (cercato sulla classe)
Cane.specie # 'Canis familiaris'బహుళ పద్ధతులు మరియు స్థితి
class Contatore:
def __init__(self, inizio=0):
self.valore = inizio
def incrementa(self, di=1):
self.valore += di
def reset(self):
self.valore = 0
c = Contatore()
c.incrementa()
c.incrementa(di=5)
c.valore # 6
c.reset()
c.valore # 0మీ వంతు
గుణాలను నిల్వ చేసే __init__(self, x, y)తో తరగతి `పాయింట్`ని నిర్వచించండి. x^2 + y^2 వర్గమూలాన్ని అందించే `distance_from_origin` పద్ధతిని జోడించండి. `p = పాయింట్(3, 4)`ని సృష్టించండి మరియు `p.distance_from_origin()`ని మూల్యాంకనం చేయండి.
సూచనను చూపించు
math.sqrt(self.x ** 2 + self.y ** 2)
3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది
వ్యాయామం సమీక్షించండి
__init__(సెల్ఫ్, బ్యాలెన్స్=0)తో `BankAccount`ని నిర్వచించండి మరియు self.balanceని సవరించే పద్ధతులు `డిపాజిట్(మొత్తం)`, `విత్డ్రా(మొత్తం)`. `a = BankAccount(100)`ని సృష్టించండి, 50 డిపాజిట్ చేయండి, 30 ఉపసంహరించుకోండి. `a.balance`ని మూల్యాంకనం చేయండి.
సూచనను చూపించు
self.balance += డిపాజిట్లో మొత్తం.
3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది
అదనపు సవాలు
Define a class `Rectangle` with a constructor `__init__(self, width, height)` to set width and height, and a method `area(self)` that returns the product of width and height. Instantiate a rectangle with width `4` and height `5` storing it in `rect`, and evaluate `rect.area()`.
సూచనను చూపించు
ప్రాంతం (స్వయం) లోపల లక్షణాలను యాక్సెస్ చేయడానికి స్వీయని ఉపయోగించాలని గుర్తుంచుకోండి.
3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది