| 
 | 
 
 
发表于 2022-5-20 02:15:07
|
显示全部楼层
 
 
 
方法是大家的,属性是自己的,要通过实例对象访问其属性,需要通过 self 进行绑定才可以哦。 
 
比如下面代码是错误的: 
 
- >>> class C:
 
 - ...     x = 100
 
 - ...     def get_x(self):
 
 - ...         print(x)
 
 - ...                
 
 - >>> c = C()
 
 - >>> c.get_x()
 
 - Traceback (most recent call last):
 
 -   File "<pyshell#6>", line 1, in <module>
 
 -     c.get_x()
 
 -   File "<pyshell#4>", line 4, in get_x
 
 -     print(x)
 
 - NameError: name 'x' is not defined
 
  复制代码 
想要访问实例的 x 属性,必须通过 self 进行绑定: 
 
- >>> class C:
 
 - ...     x = 100
 
 - ...     def get_x(self):
 
 - ...         print(self.x)
 
 - ...                
 
 - >>> c = C()
 
 - >>> c.x = 250
 
 - >>> c.get_x()
 
 - 250
 
  复制代码 
当然你可以这样来访问类属性: 
 
- >>> class C:
 
 - ...     x = 100
 
 - ...     def get_x(self):
 
 - ...         print(C.x)
 
 - ...                
 
 - >>> c = C()
 
 - >>> c.x = 250
 
 - >>> c.get_x()
 
 - 100
 
  复制代码 |   
 
 
 
 |