class Person(object): def __init__(self, name, age): self.name = name # 實例變量 self.age = age # 實例變量 p1 = Person("Tom", 18) print(p1.name) # Tom 訪問實例變量 p1.name = "Andy" # 修改實例變量的值 print(p1.name) # Andy
class Foo(object): count = 0 # 類變量 def __init__(self): Foo.count += 1 print(Foo.count) # 0 訪問類變量 Foo() Foo() Foo() print(Foo.count) # 3
class User(object): def login(self): # 實例方法 print("歡迎登陸") u = User() u.login() # 調用實例方法
語法:函數
@classmethod def 方法名(cls): pass
class Foo(object): @classmethod def add(cls, a, b): # 類方法 print(cls) return a + b print(Foo) print(Foo.add(1, 2)) 結果: <class '__main__.Foo'> <class '__main__.Foo'> 3
語法:spa
@staticmethod def 方法名.(): pass
class Foo(object): @staticmethod def welcome(): print("---Welcoming---") Foo.welcome() # ---Welcoming---
在Python中使用"__"做爲方法或者變量的前綴,那麼這個方法或者變量就是一個私有的code
若是類中存在繼承關係,子類是沒法繼承父類的私有內容的對象
class Person(object): def __init__(self, salary): self.__salary = salary def sal(self): print(self.__salary) p1 = Person(50000) print(p1.__salary) # 報錯 p1.sal() # 50000
class Person(object): def __init__(self, name, salary): self.name = name self.__salary = salary def __sal(self): print(self.__salary) def display(self): self.__sal() p1 = Person("Tom", 50000) p1.display() # 50000
注意:blog
class Person(object): def __init__(self, name, birthday): self.name = name self.birthday = birthday @property def age(self): return 2018 - self.birthday p = Person("Tom", 1994) print(p.age) # 24
增長方法,使之能夠賦值:繼承
class Test(object): def __init__(self): self.__num = 100 @property def num(self): return self.__num @num.setter def num(self, new_num): self.__num = new_num t = Test() print(t.num) # 100 t.num = 50 print(t.num) # 50
property另外一種表達方式:內存
property(fget=None, fset=None, fdel=None, doc=None)get
class Test(object): def __init__(self): self.__num = 100 def getnum(self): return self.__num def setnum(self, new_num): self.__num = new_num num = property(getnum, setnum) p1 = Test() print(p1.num) # 100 p1.num = 50 print(p1.num) # 50
觸發:對象()string