Python Projects for Beginners a ten-Week Bootcamp Approach to Python Programming


Incrementing Attributes with Methods



Download 2,61 Mb.
bet115/200
Sana20.06.2022
Hajmi2,61 Mb.
#681748
1   ...   111   112   113   114   115   116   117   118   ...   200
Bog'liq
Python Projects for Beginners A Ten Week Bootcamp Approach to Python

Incrementing Attributes with Methods


Like setters, when you want to alter an attributes value by incrementing or decrementing it rather than just changing it completely, the best way is to create a method to complete the task:

# incrementing/decrementing attribute values with methods, best programming practice class Dog( ): age = 5 def happyBirthday(self): self.age += 1 sam = Dog( ) sam.happyBirthday( ) # calls method to increment value by one print(sam.age) # better practice use getters, this is for testing purposes

Go ahead and run the cell. For this example, we created a method called happyBirthday that will increment the age of the dog by one each time it is called. This is simply better practice, but not a required method of altering class attribute values.

Methods Calling Methods


When calling a method from another method, you need to use the self parameter. Let’s create a getter method and a method that prints out the information of the dog based on the value:

1| # calling a class method from another method 3| class Dog( ):
4| age = 6 6| def getAge(self):
7| return self.age 9| def printInfo(self):
10| if self.getAge( ) < 10: # need self to call other method for an instance
11| print("Puppy!")
13| sam = Dog( )
15| sam.printInfo( )

Go ahead and run the cell. We’ll get an output of “Puppy” here. We can get the returned value from our getter because of how we referenced the getAge method within our printInfo method. It was using the self keyword and dot syntax. The condition proved true, as the returned value was 6, so it proceeded to run the print statement within the block.

Magic Methods


While they have a funny name, magic methods are the underlying of classes in Python. Without knowing, you’ve already used one, the initialization method. All magic methods have two underscores before and after their name. When you print out anything, you’re accessing a magic method called __str__. When you use operators (+, -, /, , ==, etc.), you’re accessing magic methods. They are essentially functions that decide what operators and other tasks in Python perform. Don’t get too hooked on them, as we won’t use them too much, but I wanted to introduce you to them. As mentioned, the __str__ magic method is called when using the print function; it stands for the string representation of a class. Let’s alter what gets printed out when we print out a class that we defined ourselves:

# using magic methods class Dog( ): def __str__(self):
return "This is a dog class" sam = Dog( ) print(sam) # will print the return of the string magic method

Go ahead and run the cell. Previously when we printed out a class, it would output the name of the class blueprint and the memory location. Now, since we altered the __str__ magic method, we were able to output a completely different print statement. Keep in mind that the __str__magic method was expecting a string to be returned, not printed. All magic methods require certain parameters and returned values. Feel free to look up a couple more and alter others to see how they work!

Download 2,61 Mb.

Do'stlaringiz bilan baham:
1   ...   111   112   113   114   115   116   117   118   ...   200




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