1. 程式人生 > >類和對象的增刪改查

類和對象的增刪改查

AI like wan spa ini python腳本 方法 一個 pri

最近寫一個簡單的python腳本,延遲了半個月的進度

接下來學習面向對象了

# 類的增刪改查

class Dog:
    def __init__(self,name,age,color):
        self.name = name
        self.age = age
        self.color = color
    def jiao(self):
        print("%s汪汪叫"%self.name)

    def eat(self,food):
        print("%s喜歡吃%s"%(self.name,food))

wangcai 
= Dog("旺財",10,"black") print(wangcai.age) wangcai.eat("meat") # 增加 def colors(self): print("{}是{}色的".format(self.name,self.color)) Dog.colors = colors wangcai.colors() Dog.like = "play ball" print(wangcai.like) # 刪除 del Dog.jiao # print(wangcai.jiao()) #會報錯 # 替換 Dog.like = "run" print(wangcai.like)
# 查詢 print(Dog.like)

# 對象的增刪改查
class Cat:
    def __init__(self,name,age,color):
        self.name = name
        self.age = age
        self.color = color
    def eat_food(self,food):
        print("%s喜歡吃%s"%(self.name,food))

c1 = Cat("miaomiao",2,"")
# 增加
c1.like ="fish"
# 查看
print(c1.__dict__
) print(c1.eat_food) # 刪除 del c1.color print(c1.__dict__) # 修改 c1.age = 3 print(c1.__dict__)

值得註意的是,直接賦值的修改對象。使用方法直接修改的是類

class Test:
    def __init__(self,name):
        self.name = name
    l = [1,2,4]

s  = Test("test")

# print(s.l)
# 賦值修改對象內容
# s.l = [1,2,3,4,5]
# print(s.l)

#操作的是類,在類中直接添加 與s無關
s.l.append("a")
print(s.l)
print(s.__dict__)#s中沒有l的字典
print(Test.l)

類和對象的增刪改查