前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 类中的单下划线和双下划线

python 类中的单下划线和双下划线

作者头像
用户5760343
发布2019-12-13 15:07:56
1.8K0
发布2019-12-13 15:07:56
举报
文章被收录于专栏:sktj

Python中没有访问控制的关键字,例如private、protected等等。但是,在Python编码中,有一些约定来进行访问控制。

1、单下划线"_"

在Python中,通过单下划线"“来实现模块级别的私有化,变量除外。一般约定以单下划线”"开头的函数为模块私有的,也就是说"from moduleName import * “将不会引入以单下划线”"开头的函数。 现在有一个模块 example_example.py,内容用如下,模块中一个变量名和一个函数名分别以""开头:

name = 'bruce' _tall = 180

def call_for(): print('name is :',name) print('_tall is',_tall)

def _call_for(): print('name is :',name)

_call_for = _call_for()

print() print('_tall is',_tall) 运行脚本输出:

_tall is 180

再次调用该脚本:

调用脚本模块example_example

import example_example

调用不带下划线变量

example_example.name Out[12]: 'bruce'

调用带下划线变量

example_example._tall #对于变量单下划线不会影响调用 Out[13]: 180

调用不带下划线函数

example_example.call_for() name is : bruce _tall is 180

调用不带下划线函数会报错

example_example._call_for() Traceback (most recent call last):

File "<ipython-input-15-e642b1386946>", line 1, in <module> example_example._call_for()

TypeError: 'NoneType' object is not callable 2、双下划线"__"

对于Python中的类属性,可以通过双下划线"__“来实现一定程度的私有化,因为双下划线开头的属性在运行时会被"混淆”(mangling)。 class person(object):

代码语言:javascript
复制
tall = 180
hobbies = []
def __init__(self, name, age,weight):
    self.name = name
    self.age = age
    self.weight = weight
    self.__Id = 430
@staticmethod
def infoma():
    print(person.tall)
    print(person.hobbies)

person.infoma()

Bruce = person("Bruce", 25,180) print(Bruce.__Id)

Bruce.infoma()

运行程序输出:

Traceback (most recent call last):

File "<ipython-input-17-20e3bf55d9a2>", line 1, in <module> runfile('C:/Users/BruceWong/.spyder-py3/类的定义构建.py', wdir='C:/Users/BruceWong/.spyder-py3')

File "C:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile execfile(filename, namespace)

File "C:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/BruceWong/.spyder-py3/类的定义构建.py", line 166, in <module> print(Bruce.__Id)

AttributeError: 'person' object has no attribute '__Id' 其实,通过内建函数dir()就可以看到其中的一些原由,"__Id"属性在运行时,属性名被改为了"_person__Id"(属性名前增加了单下划线和类名)

print(dir(Bruce))

可以看到Bruce中有_person__Id的属性,相较原__Id属性,变得可调用

['class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref', '_person__Id', 'age', 'hobbies', 'infoma', 'name', 'tall', 'weight']

所以说,即使是双下划线,也没有实现属性的私有化,因为通过下面的方式还是可以直接访问"__Id"属性:

class person(object):

代码语言:javascript
复制
tall = 180
hobbies = []
def __init__(self, name, age,weight):
    self.name = name
    self.age = age
    self.weight = weight
    self.__Id = 430     #############
@staticmethod
def infoma():
    print(person.tall)
    print(person.hobbies)

person.infoma()

Bruce = person("Bruce", 25,180) print(Bruce._person__Id)

Bruce.infoma()

输出运行结果:

430 #通过使属性_Id名前增加了单下划线和类名person来实现属性的可调用 1 双下划线的另一个重要的目地是,避免子类对父类同名属性的冲突 class A(object): def init(self): self.__private() self.public()

代码语言:javascript
复制
def __private(self):
    print('A.__private()')

def public(self):
    print('A.public()')

class B(A): def __private(self): print('B.__private()')

代码语言:javascript
复制
def public(self):
    print('B.public()')

b = B() 输出:

A.private() B.public() 1 2 当实例化B的时候,由于没有定义 _ init 函数,将调用父类的 _ init_ _,但是由于双下划线的"混淆"效果,"self.__private()"将变成 “self._A__private()”。

总结: "__“和” _ __"的使用 更多的是一种规范/约定,并没有真正达到限制的目的:

”:以单下划线开头的表示的是protected类型的变量,即只能允许其本身与子类进行访问;同时表示弱内部变量标示,如,当使用"from moduleNmae import *"时,不会将以一个下划线开头的对象引入。 _”:双下划线的表示的是私有类型的变量。只能是允许这个类本身进行访问了,连子类也不可以,这类属性在运行时属性名会加上单下划线和类名。 ———————————————— 版权声明:本文为CSDN博主「brucewong0516」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/brucewong0516/article/details/79120841

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • _call_for = _call_for()
  • 调用脚本模块example_example
  • 调用不带下划线变量
  • 调用带下划线变量
  • 调用不带下划线函数
  • 调用不带下划线函数会报错
  • person.infoma()
  • Bruce.infoma()
  • 可以看到Bruce中有_person__Id的属性,相较原__Id属性,变得可调用
  • person.infoma()
  • Bruce.infoma()
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档