1.之前我理解类是为了节省时间演化来的,因此里面的类的静态属性应该和模块中的全局变量作用范围类似,那类中的静态属性应该在整个类中都能访问。但实际为代码段所示。
2.
2.1 全局变量能被内部定义函数所访问:
c=10
def glass(x):
return x*c
>>> glass(5) #能访问全局变量
50
2.实例对象中的方法直接访问静态属性:
class A:
c=10
def glass(self,x):
return x*c #除非改成return x*self.c
>>> a=A()
>>> a.glass(5)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
a.glass(5)
File "F:/new/new world/ex45/delete.all1.py", line 4, in glass
return x*c
NameError: name 'c' is not defined
对,这是规定,否则无法区分类属性和全局变量
c = 5
class A:
c=10
def glass(self,x):
return x*c #除非改成return x*self.c
//考虑一下这句的运行结果
print(A().glass(5))