Python中__init__和self的意義和作用


 

init()方法,在創建一個對象時默認被調用,不需要手動調用

#init方法
class Car():
    def __init__(self):
         self.num = 4
         self.color = '紅色'
    def taxi(self):
        print("出發去西湖!")
#創建對象
test = Car()
print("車的顏色為:%s"%test.color)
print("車輪胎的數量:%s"%test.num)

'''結果輸出:'''

#車的顏色為:紅色
#車輪胎的數量:4

 

有了__init__方法,在創建實例的時候,就不能傳入空的參數了,必須傳入與__init__方法匹配的參數,但self不需要傳,Python解釋器自己會把實例變量傳進去:

如果不傳參數的話則會報錯:TypeError: __init__() missing 2 required positional arguments: 'name' and 'age'

#init方法
class Sutdent:
    def __init__(self,name,age):
         self.name = name
         self.age = age
    def taxi(self):
        print("出發去西湖!")
#創建對象
test = Sutdent('Sample_天',3)
print("學生姓名:%s"%test.name)
print("學生年齡:%s"%test.age)

#學生姓名:Sample_天
#學生年齡:3



 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM