python 對象的初始狀態(構造函數)


class Person(object):
#name = "stu"
#age = 10
#height = 160
#weight = 90
def run(self):
print("run")
def eat(self, food):
print("eat " + food)

def __init__(self, name, age, height, weight):
#print(name, age, height, weight)
#定義屬性
self.name = name
self.age = age
self.height = height
self.weight = weight

'''
構造函數:__init__() 在使用類創建對象的時候自動調用
注意:如果不顯示的寫出構造函數,默認會自動添加一個空的構造函數
'''
per = Person("hanmeimei", 20, 170, 55)
print(per.name, per.age)

per2 = Person("lilei", 21, 175, 70)
print(per2.name, per2.age)

per.run()


免責聲明!

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



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