1.xx
一般情况下使用的变量
两种模块的导入方法:
import TestModule1
print(TestModule1.PI)
from TestModule1 import *
print(PI)
TestModule1 模块:
PI = 3.14
2._xx
_PI = 3.14
在某个模块中,如果变量是_xx形式的
使用from import * 的方式将无法使用
import TestModule1
print(TestModule1._PI)
TestModule1 模块:
_PI = 3.14
3.__xx
私有属性/私有方法
名字重整(改名)
重整的原则:
_类名__私有属性名
_类名__私有方法名
class Person():
def __init__(self,name,age):
self.name = name
self.__age = age#私有属性
def showInfo(self):
print("name:%s age:%d"%(self.name,self.__age))
def __test(self):#私有方法
print("我是Person类中的私有方法")
p = Person('Dawei',18)
p.showInfo()
print(p.name)
#print(p.__age) 出现错误
#p.__test() 出现错误
解决方法:
print(dir(p))
print(p._Person__age)
p._Person__test()
print(dir(\p))运行结果:
[‘_Person__age’, ‘_Person__test’, ‘class’, ‘delattr’, ‘dict’, ‘dir’, ‘doc’, ‘eq’, ‘format’, ‘ge’, ‘getattribute’, ‘gt’, ‘hash’, ‘init’, ‘init_subclass’, ‘le’, ‘lt’, ‘module’, ‘ne’, ‘new’, ‘reduce’, ‘reduce_ex’, ‘repr’, ‘setattr’, ‘sizeof’, ‘str’, ‘subclasshook’, ‘weakref’, ‘name’, ‘showInfo’]
4.__xx__
主要用于方法
__init__
__del__
__new__
__str__
Magic Methond
自定义方法避免与魔法方法重名
5.xx_
用来区分变量名/方法名