day24
面向對象三大特性:封裝
self參數
1 class Bar: 2 def foo(self, arg): 3 print(self, arg) 4 5 x = Bar() 6 print(x) 7 8 x.foo(112358) 9 print('/////////////////////////////////////////') 10 y = Bar() 11 print(y) 12 13 y.foo(112) 14 15 #self指調用方法的對象
self指調用方法的對象
執行結果:
<__main__.Bar object at 0x7fae0e065780> <__main__.Bar object at 0x7fae0e065780> 112358 ///////////////////////////////////////// <__main__.Bar object at 0x7fae0e065828> <__main__.Bar object at 0x7fae0e065828> 112 Process finished with exit code 0
對象可以存值
1 class Bar: 2 def foo(self, arg): 3 print(self, self.name, self.age, arg) 4 5 x = Bar() 6 x.name = 'nizhipeng' 7 x.age = 18 8 9 x.foo(1123) 10 11 y = Bar() 12 y.name = 'nizsvsd' 13 y.age = 20 14 15 y.foo(113)
執行結果:
1 <__main__.Bar object at 0x7fdadb4f5828> nizhipeng 18 1123
2 <__main__.Bar object at 0x7fdadb4f5860> nizsvsd 20 113
3
4 Process finished with exit code 0
封裝(面向對象的三大特性之一)
1 class Bar: 2 def foo(self, arg): 3 print(self.name, self.age, arg) 4 5 obj = Bar() 6 #將公共變量封裝進對象中 7 obj.name = "nizhipeng" 8 obj.age = "18" 9 obj.foo("112358")
將公共變量封裝進對象中,為封裝。
nizhipeng 18 112358
Process finished with exit code 0