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

本文详细介绍了Python中的访问控制机制,包括单下划线和双下划线的作用与使用方法,解释了如何通过这些约定实现类似私有成员的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 "", line 1, in

example_example._call_for()

TypeError: 'NoneType' object is not callable

2、双下划线"__"

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

class person(object):

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 "", line 1, in

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

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):

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()

def __private(self):

print('A.__private()')

def public(self):

print('A.public()')

class B(A):

def __private(self):

print('B.__private()')

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值