wenwen
wenwen

探索網路世界和進入區塊鏈的過程或許很平凡,但我就是想分享給大家,若能幫助到有需要幫助的人,那就更好了。 有幫到你的話,記得按下方拍手圖,不需花你任何金錢,免費註冊Liker ID,就可對我化讚為賞:https://button.like.co/willie5068

013第九章 CLASSES_續1_init()方法和self的關係

覺得 對於 instance 和 Class 中 的 __init__() 方法中的 self 的關係和觀念通了

💛20230113晨讀感言:

💔複習了昨日所看的 class 定義中的 `__init()__` 方法 和 瞭解 instance 和 self 的關係, 就花了我 40分鐘,沒辦法,這是運用 Class 的基礎觀念,不將基礎打好穩固不行。

💔總結一句話,當你==經由 Class 建立 instance時(即在程式中,將Class名稱後面接上(),這就完成 instance 的建立,例 Dog() )==, python 會自動 經由Class 裡的 `__init()__` 建立 self 來參照這個 instance ,然後 將 parameter 「name」 裡面的值 連結 到 「self.變數 」 ,即 self.name = name ) ==。

💛晨讀摘要:

💚159 The Dog class has two other methods defined: sit() and roll_over() . Because these methods don’t need additional information like a name or age, we just define them to have ==one parameter, self. The instances we create later will have access to these methods==.

💚160 Let’s make an instance representing a specific dog. At 「my_dog = Dog(‘Willie’, 6) 」.we tell Python to create a dog whose name is ‘willie’ and whose age is 6. When Python reads this line, it calls the `__init()__` method in Dog with the arguments ‘willie’ and 6. The `__init()__` method creates an instance representing this particular dog and sets the name and age attributes using the values we provided. ==The `__init()__` method has no explicit return statement, but Python automatically returns an instance representing this dog==. We store that instance in the variable my_dog. The naming convention is helpful here: we can usually assume that a capitalized name like Dog refers to a class, and a lowercase name like my_dog refers to a single instance created from a class.

💚160 Accessing Attributes :To access the attributes of an instance, you use dot notation. we access the value of my_dog’s attribute name by writing: 「my_dog.name」.

💚161 Calling Methods : To call a method, give the name of the instance (in this case, my_dog) and the method you want to call, separated by a dot. When Python reads my_dog.sit(), it looks for the method sit() in the class Dog and runs that code.

💚164 Modifying Attribute Values :You can change an attribute’s value in three ways: you can change the value directly through an instance, set the value through a method, or increment the value (add a certain amount to it) through a method.

💚166 You can use methods like this to control how users of your program update values such as an odometer reading, but anyone with access to the program can set the odometer reading to any value by accessing the attribute directly. ==Effective security takes extreme attention to detail in addition to basic checks like those shown here==.

from :《python crash course》

CC BY-NC-ND 2.0 版权声明

喜欢我的文章吗?
别忘了给点支持与赞赏,让我知道创作的路上有你陪伴。

加载中…
加载中…

发布评论