Python中類的使用(2創建類,實例化對象,進行訪問修改)



#創建類
class Person(object):
# 定義屬性(定義變量)
name = ""
age = 0
height = 0
weight = 0
def run(self):
print("run")
def eat(self, food):
print("eat" + food)
def openDoor(self):
print("我已經打開了冰箱")
def fillEle(self):
print("我已經把水果放進冰箱")
def closeDoor(self):
print("我已經關閉了冰箱")

#實例化對象
#格式:對象名=類名(參數列表)
#注意:沒有參數,小括號也要有
per1=Person()   #實例化對象
print(per1)     #<__main__.Person object at 0x005FEAF0>內存地址
print(type(per1))
print(id(per1))
per2=Person()
print(per2)
print(type(per2))
print(id(per2))
#訪問屬性
#格式:對象名.屬性名
#賦值:對象名.屬性名=新值
#添加修改對象屬性
per.name="tom"
per.age=18
per.height=170
per.weight=80
print(per.name,per.age,per.height,per.weight)

#訪問方法
#格式:對象名.方法名(參數列表)

per.openDoor()
per.run()

#問題?當前Person所有對象的屬性都是相同的


免責聲明!

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



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