本文主要记录了python中一些特殊变量或者属性的说明,比如__all__
等。
__all__
先看代码,假设有两个py文件,
test.py
import re
def f():
print('test:f')
def f1():
print('test:f1')
test1.py
from test import *
f()
f1()
print(re.findall('\d', '123'))
运行test1.py是不会报错的,但是我们看见我们用了re
模块,test1.py里面却没有使用import re
引入,为什么呢,因为我们在import test
的时候,test.py里面引入了re
,所以我们在这里也可以使用。另外,如果我在test.py里面定义的某些内容,不想其它模块使用,比如这里f1
这个函数,我只想别人用我的f
函数,f1
不能使用,那么__all__
变量就可以解决这个问题。
当我们修改test.py为如下格式后:
import re
__all__ = [
'f'
]
def f():
print('test:f')
def f1():
print('test:f1')
test1.py就只能使用f
函数了,re
和f1
都是不能使用的。
注意:
__all__
只针对import *
这种格式有效,如果要访问f1
或者re
,其它模块仍然可以使用test.f1
或者test.re
这种限定访问符的方式来访问。
__name__
The name of the class, function, method, descriptor, or generator instance.
__main__
如果模块在被直接执行的时候__name__
就等于__main__
,如果是被导入__name__
就等于模块的文件名
__dict__
A dictionary or other mapping object used to store an object’s (writable) attributes.
就是一个字典,存储了对应对象的属性。
__slots__
它是一个列表,是一个类属性,如果设置了这个属性,那么__dict__
就无效了,只有定义在__slots__
列表里面的属性才可以进行获取或者配置,使用这个属性,我们可以防止用户随意产生属性,比如:
class A(object):
def __init__(self):
self.a = 1
上面没有使用__slots__
,那么用户可以做下面的操作:
x = A()
x.a = 2
x.b = 1 #这个是用户自己加入的
如果类的定义增加了__slots__
,我们可以防止用户访问或者设置不应该有的属性:
class A(object):
__slots__ = ['a']
def __init__(self):
self.a = 1
那么用户在用x.b = 1
的时候会抛出异常AttributeError: 'A' object has no attribute 'b'
注意:这个属性,只是针对类的实例有效,如果直接对类设置了一个不在
__slots__
里面的属性,这个属性可以设置成功,而且类的实例也可以访问,比如:
class A(object):
__slots__ = ['a']
def __init__(self):
self.a = 1
A.b = 2
x = A()
print(x.b)
我们虽然限定了__slots__ = ['a']
,但是我们对A.b = 2
,那么下面的print
仍然可以打印出结果,而且不会报错。
网友评论