類的成員有兩種形式
公有成員,在任何地方都能訪問
私有成員,只有在類的內部才能方法,私有成員命名時,前兩個字符是下劃線。
class Foo: def __init__(self, name, age): self.name = name self.__age = age def show(self): # 間接方法私有字段 return self.__age obj = Foo('klvchen', 25)print(obj.name)res = obj.show()print(res)
運行結果:
klvchen
25
公有靜態字段:類可以訪問;類內部可以訪問;派生類中可以訪問
私有靜態字段:僅類內部可以訪問;
class Foo: __v = '666' # 私有靜態字段 def __init__(self): pass def show(self): return Foo.__vobj = Foo()res = obj.show()print(res)
運行結果:
666
class Foo: __v = '666' def __init__(self): pass def show(self): return Foo.__v @staticmethod def stat(): return Foo.__vres = Foo.stat()print(res)
運行結果:
666
無法從父類繼承私有字段
class F: def __init__(self): self.ge = 123 self.__gene = 456 #私有字段class S(F): def __init__(self, name): self.name = name self.__age = 18 super(S, self).__init__() def show(self): print(self.name) print(self.__age) print(self.ge) print(self.__gene)s = S('klvchen')s.show()
運行結果:
klvchen
18
123
AttributeError: 'S' object has no attribute '_S__gene'
類的特殊成員
int(對象),會自動執行對象中的__int__方法,并將返回賦值給 int 對象,同理 str(對象),會自動執行__str__方法,并返回賦值給 str 對象。
class Foo: def __init__(self): pass def __int__(self): return 666 def __str__(self): return 'hello world'obj = Foo()print(obj, type(obj))res = int(obj)print(res)res1 = str(obj)print(res1)
運行結果:
<__main__.Foo object at 0x0000022BBE9DA978> <class '__main__.Foo'>
666
hello world
print(對象),str(對象),都會自動執行對象中的__str__方法,并返回
class Foo: def __init__(self, n, a): self.name = n self.age = a def __str__(self): return '%s-%d' %(self.name, self.age)obj = Foo('klvchen', 28)print(obj)
運行結果:
klvchen-28
兩個對象相加時,自動執行第一對象的__add__方法,并且將第二個對象當參數傳遞進去
class Foo: def __init__(self, name, age): self.name = name self.age = age def __add__(self, other): return self.age + other.ageobj1 = Foo('klv1', 23)obj2 = Foo('klv2', 24)res = obj1 + obj2print(res, type(res))
新聞熱點
疑難解答