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