python引用模块的私有变量_python 使用不同方法导入模块,模块中私有变量的使用区别...

文章目录

from somemodule import *import somemodule

首先我们先创建一个test.py文件,将下面代码复制进去:

num = 10

_num = 20

__num = 30

def test():

print("--test--")

def _test2():

print("--test2--")

def __test3():

print("---test3--")

from somemodule import *

在使用 from somemodule import * 导入模块的情况下,不能导入或使用私有属性和方法。

>>> from test import *

>>> num

10

>>> _num

Traceback (most recent call last):

File "", line 1, in

NameError: name '_num' is not defined

>>> __num

Traceback (most recent call last):

File "", line 1, in

NameError: name '__num' is not defined

>>> test()

--test--

>>> _test2

Traceback (most recent call last):

File "", line 1, in

NameError: name '_test2' is not defined

>>> __test3()

Traceback (most recent call last):

File "", line 1, in

NameError: name '__test3' is not defined

import somemodule

在使用 import somemodule 导入模块的情况下,能导入并使用私有属性和方法。

>>> import test

>>> test.num

10

>>> test._num

20

>>> test.__num

30

>>> test._test()

Traceback (most recent call last):

File "", line 1, in

AttributeError: module 'test' has no attribute '_test'

>>> test.test()

--test--

>>> test._test2()

--test2--

>>> test.__test3()

---test3--

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值