Python全棧學習筆記day 23:面向物件2、名稱空間、組合
阿新 • • 發佈:2018-11-05
__init__方法 :初始化方法
python幫我們建立了一個物件self
每當我們呼叫類的時候就會自動觸發這個方法。預設傳self
在init方法裡面可以對self進行賦值
self:
self擁有屬性都屬於物件
在類的內部,self就是一個物件
類可以定義兩種屬性:靜態屬性、動態屬性
類中的靜態變數:可以被物件和類呼叫
對於不可變資料型別來說,類變數最好用類名操作
對於可變資料型別來說,物件名的修改是共享的,重新賦值是獨立的
栗子:
class Person: money = 0 def work(self): Person.money += 1000 mother = Person() father = Person() mother.money += 1000 father.money += 1000 print(Person.money) 輸出:0
class Person:
money = 0
def work(self):
Person.money += 1000
mother = Person()
father = Person()
Person.money += 1000
Person.money += 1000
print(Person.money) 輸出:2000
栗子2:建立一個類,每例項化一個物件就計數,最終所有的物件共享這個資料
class Foo: count = 0 def __init__(self): Foo.count += 1 f1 = Foo() f2 = Foo() print(f1.count) 2 print(f2.count) 2 f3 = Foo() print(f1.count) 3
組合 :一個物件的屬性值是另外一個類的物件 在下面這個例子中:
物件:alex 屬性值:weapon 是 weapon的物件
栗子2:建立一個老師類,老師有生日,生日也是一個類,要使用組合
class Birthday: def __init__(self,year,month,day): self.year = year self.month = month self.day = day class Course: def __init__(self,course_name,period,price): self.name = course_name self.period = period self.price = price class Teacher: def __init__(self,name,age,sex,birthday): self.name = name self.age = age self.sex = sex self.birthday =birthday self.course = Course('python','6 month',2000) b = Birthday(2018,1,16) egg = Teacher('egon',0,'女',b) print(egg.name) print(egg.birthday.year) 組合 print(b.year) print(egg.birthday.month) 組合 print(b.month) print(egg.course.price) 組合