26类和对象---名称空间

类也有独立完备的命名空间,同时类支持命名空间的继承
实例只有数据属性,没有函数属性,但是可以在类属性中找到函数属性

A.name = 'cc'
print(A.name) # 'cc',此时,类还没有实例。其实,类本身也是对象,也可以为其添加自己的属性

 

a = A() # 实例化对象
print(a.name) # 此时对象a的名称空间内没有name,这个name继承自类A
a.name = 'mm'
print(a.name) # 会先在自己的名称空间内找到name='mm'
print(A.name) # 'cc',类的数据属性

 

 

# 好好理解,python学习手册699页
x = 11  # global
def f():
    print(x)
def g():
    x = 22 # local,函数的本地变量
    print(x)
class C:
    x = 33 # 类的数据属性,class attribute
    def m(self):
        x = 44 # 方法(函数)m中的本地变量
        self.x = 55 # 实例的数据属性,instance attribute

 

类的作用域犯的一错误:

x1 = 11
class A:
    x2 = 22
    def fun(self):
        print(x1) # 可以访问,类能够访问外层函数的作用域
        print(x2) # 报错,类不能作为类中其它代码的外层作用域

 

posted @ 2021-04-05 14:36  cheng4632  阅读(54)  评论(0编辑  收藏  举报