Author Dusty Phillips Reviewers



Download 2,95 Mb.
Pdf ko'rish
bet41/183
Sana20.07.2022
Hajmi2,95 Mb.
#831085
1   ...   37   38   39   40   41   42   43   44   ...   183
Bog'liq
python3-oop

Talking to yourself
The one difference between methods and normal functions is that all methods have 
one required argument. This argument is conventionally named 
self
; I've never seen 
a programmer use any other name for this variable (convention is a very powerful 
thing). There's nothing stopping you, however, from calling it 
this
or even 
Martha
.
The 
self
argument to a method is simply a reference to the object that the method 
is being invoked on. We can access attributes and methods of that object as if it were 
any another object. This is exactly what we do inside the 
reset
method when we set 
the 
x
and 
y
attributes of the 
self
object.
www.it-ebooks.info


Chapter 2
[
 31 
]
Notice that when we call the 
p.reset()
method, we do not have to pass the 
self
argument into it. Python automatically takes care of this for us. It knows we're calling
a method on the 
p
object, so it automatically passes that object to the method.
However, the method really is just a function that happens to be on a class. Instead 
of calling the method on the object, we can invoke the function on the class, explicitly 
passing our object as the 
self
argument:
p = Point()
Point.reset(p)
print(p.x, p.y)
The output is the same as the previous example because internally, the exact same 
process has occurred.
What happens if we forget to include the 
self
argument in our class definition? 
Python will bail with an error message:
>>> class Point:
... def reset():
... pass
...
>>> p = Point()
>>> p.reset()

Download 2,95 Mb.

Do'stlaringiz bilan baham:
1   ...   37   38   39   40   41   42   43   44   ...   183




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©hozir.org 2024
ma'muriyatiga murojaat qiling

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish