网络编程
位置:首页>> 网络编程>> Python编程>> python 函数、变量中单下划线和双下划线的区别详解

python 函数、变量中单下划线和双下划线的区别详解

作者:岳来  发布时间:2021-06-29 11:32:33 

标签:python,单下划线,双下划线

一、_func 单下划线开头 --口头私有变量

1.1、在模块中使用单下划线开头

在Python中,通过单下划线_来实现模块级别的私有化,变量除外。一般约定以单下划线开头的函数为模块私有的,也就是说from moduleName import * 将不会引入以单下划线开头的函数。模块中使用单下划线开头定义函数、全局变量和类均适用,但可以用:from module import _func形式单独导入。

实例如下:

lerarn_under_line.py

# coding=utf-8
course = "math"
_credit = 4

def call_var():
    print "course:%s" % course
    print "_credit:%d" % _credit

def _call_var():
    print "带下划线course:%s" % course
    print "带下划线_credit:%d" % _credit

def __call_var():
    print "带双下划线course:%s" % course
    print "带双下划线_credit:%d" % _credit

import lerarn_under_line

>>> import lerarn_under_line
>>> lerarn_under_line.call_var
<function call_var at 0x10aa61850>
>>> lerarn_under_line.call_var()
course:math
_credit:4
>>> lerarn_under_line._call_var()   # 单下划线可以调用
带下划线course:math
带下划线_credit:4
>>> >>> lerarn_under_line.__call_var()   # 双下划线不可调用
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '__call_var'

from lerarn_under_line import *

>>> from lerarn_under_line import *
>>> course
'math'
>>> _credit
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_credit' is not defined
>>> call_var()
course:math
_credit:4
>>> _call_var()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_call_var' is not defined
>>> __call_var()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '__call_var' is not defined

from module import _func

>>> from lerarn_under_line import course
>>> course
'math'
>>> from lerarn_under_line import _credit
>>> _credit
4
>>> from lerarn_under_line import call_var
>>> call_var()
course:math
_credit:4
>>> from lerarn_under_line import _call_var
>>> _call_var()
带下划线course:math
带下划线_credit:4
>>> from lerarn_under_line import __call_var
>>> __call_var()
带双下划线course:math
带双下划线_credit:4

1.2、在类中使用单下划线开头

lerarn_under_line.py

class Course(object):
    def __init__(self, name):
        self.name = name

    def credit(self):
        if self.name == 'math':
            print "%s的credit 为%d" % (self.name, 4)
        else:
            print "%s的credit 为%d" % (self.name, 2)

    def _credit(self):
        if self.name == 'math':
            print "%s的credit 为%d" % (self.name, 4)
        else:
            print "%s的credit 为%d" % (self.name, 2)

    def __credit(self):
        if self.name == 'math':
            print "%s的credit 为%d" % (self.name, 4)
        else:
            print "%s的credit 为%d" % (self.name, 2)

import lerarn_under_line

>>> import lerarn_under_line
>>> a=Course('math')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Course' is not defined

from lerarn_under_line import *

>>> from lerarn_under_line import *
>>> a=Course('math')
>>> a.credit()
math的credit 为4
>>> a._credit()
math的credit 为4
>>> a.__credit()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Course' object has no attribute '__credit'

from lerarn_under_line import Course

>>> from lerarn_under_line import Course
>>> a=Course('math')
>>> a.__credit()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Course' object has no attribute '__credit'
>>> a._credit()
math的credit 为4
>>> a.credit()
math的credit 为4

综上,单下划线开头的函数表示是口头实例私有变量,是可访问的,但是也不要随意访问,即所谓防君子不防小人。

二、__func 双下划线开头的函数 --私有变量

2.1、在模块中使用双下划线开头

在实例中,带双下划线的类变量、实例变量、方法不能被直接访问。但有办法间接访问。如1.1中的from module import __func

>>> from lerarn_under_line import *
>>> __call_var()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '__call_var' is not defined

>>> import lerarn_under_line
>>> lerarn_under_line.__call_var()   # 双下划线不可调用
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '__call_var'

>>> from lerarn_under_line import course
>>> from lerarn_under_line import __call_var
>>> __call_var()
带双下划线course:math
带双下划线_credit:4

2.2、在类中使用双下划线开头

  • 在class类的内部,带双下划线的类变量、实例变量、方法具有正常访问权限。

  • 在继承结构中,带双下划线的基类的类变量和实例变量不能被子类直接访问。

lerarn_under_line.py

class Course(object):
    def __init__(self, name, _teacher, __classroom):
        self.name = name
        self._teacher = _teacher
        self.__classroom = __classroom

    def call_var(self):
        print "name:%s" % self.name
        print "_teacher:%s" % self._teacher
        print "__classroom:%s" % self.__classroom   
>>> import lerarn_under_line
>>> a = Course('math', 'zhangyu', 'juyiting')  # 无法实例化
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Course' is not defined
>>> from lerarn_under_line import *
>>> a = Course('math', 'zhangyu', 'juyiting')
>>> a.call_var()
name:math
_teacher:zhangyu
__classroom:juyiting

lerarn_under_line.py

class Course(object):
    def __init__(self, name, _teacher, __classroom):
        self.name = name
        self._teacher = _teacher
        self.__classroom = __classroom

    def call_var(self):
        print "name:%s" % self.name
        print "_teacher:%s" % self._teacher
        print "__classroom:%s" % self.__classroom

class SonCourse(Course):
    def __init__(self, name, _teacher, __classroom, time):
        super(Course, self).__init__()
        self.time = time
        self.name = name
        self.__classroom = self.__classroom
        self._teacher = self._teacher
        self.__classroom = self.__classroom

    def call_son_var(self):
        print "time:%s" % self.time
        print "name:%s" % self.name
        print "_teacher:%s" % self._teacher
        print "__classroom:%s" % self.__classroom
>>> import lerarn_under_line
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "lerarn_under_line.py", line 77, in <module>
    b = SonCourse('math', 'zhangyu', 'juyiting', "12:00")
  File "lerarn_under_line.py", line 63, in __init__
    self.__classroom = self.__classroom
AttributeError: 'SonCourse' object has no attribute '_SonCourse__classroom'

>>> from lerarn_under_line import *
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "lerarn_under_line.py", line 77, in <module>
    b = SonCourse('math', 'zhangyu', 'juyiting', "12:00")
  File "lerarn_under_line.py", line 63, in __init__
    self.__classroom = self.__classroom
AttributeError: 'SonCourse' object has no attribute '_SonCourse__classroom'

>>> from lerarn_under_line import Course
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "lerarn_under_line.py", line 77, in <module>
    b = SonCourse('math', 'zhangyu', 'juyiting', "12:00")
  File "lerarn_under_line.py", line 63, in __init__
    self.__classroom = self.__classroom
AttributeError: 'SonCourse' object has no attribute '_SonCourse__classroom'

>>> from lerarn_under_line import sonCourse
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "lerarn_under_line.py", line 77, in <module>
    b = SonCourse('math', 'zhangyu', 'juyiting', "12:00")
  File "lerarn_under_line.py", line 63, in __init__
    self.__classroom = self.__classroom
AttributeError: 'SonCourse' object has no attribute '_SonCourse__classroom'

三、前后都有双下划线 --特殊变量

Python保留了有双前导和双末尾下划线的名称,用于特殊用途。 这样的例子有,init__对象构造函数,或__call &mdash; 它使得一个对象可以被调用。这些方法通常被称为神奇方法,最好避免在自己的程序中使用以双下划线开头和结尾的名称,以避免与将来Python语言的变化产生冲突。

常见方法:

方法含义
__str__当将对象转换成字符串时会执行
__init__初始化方法,为对象变量赋值
__new__构造方法,创建一个对象
__call__在对象后面加括号会执行该方法
__getattr__当使用对象.属性时,若属性不存在会调用该方法
__setattr__当使用对象.属性 = 值,会调用该方法
__iter__类内部定义了该方法,对象就变成了可迭代对象
__add__当两个对象使用+号会调用该方法
__enter__和__exit__上下文管理

参考文档

1、https://blog.csdn.net/brucewong0516/article/details/79120841

2、http://t.zoukankan.com/one-tom-p-11749739.html

3、https://www.cnblogs.com/bryant24/p/11429653.html

4、https://blog.csdn.net/m0_58357932/article/details/121062461

5、https://www.likecs.com/show-308380836.html

来源:https://blog.csdn.net/yuelai_217/article/details/128706898

0
投稿

猜你喜欢

  • 在python显示图象时,我们用matplotlib模块时会遇到图像色彩失真问题,究竟是什么原因呢,下面就来看看究竟。待显示图像为:impo
  • 基于smtplib包制作而成,但在实践中发现一个不知道算不算是smtplib留的一个坑,在网络断开的情况下发送邮件时会抛出一个socket.
  • SQL中的单记录函数1.ASCII返回与指定的字符对应的十进制数;SQL> select ascii('A') A,a
  • 为什么选择Python进行数据分析?Python是一门动态的、面向对象的脚本语言,同时也是一门简约,通俗易懂的编程语言。Python入门简单
  • 环境系统:Centos7.2 服务:Nginx1:下载PHP7.0.2的安装包解压,编译,安装: $ cd /usr/s
  • 下午在写程序的时候,碰到个变量重定义的问题,具体是在一个函数中的两个地方定义了相同的变量,两个变量分别放在IF语句的两部分中,本来以为这两次
  • 1.样式的重用性CSS布局的网页最大的特点就是样式的可重用性,利用class选择符重复将某个样式属性多次在网页中使用,以减少不断定义样式属性
  •     作为一个网页设计师,不知道各位是否有这样的经历:客户给你的网站材料很多都是Word文档,虽然阅读起来很
  • 1. auth介绍Django 自带一个用户验证系统。它负责处理用户账号、组、权限和基于cookie的用户会话。认证系统由以下部分
  • 在实际的工作中会经常会用到to_char()、to_date()函数来对时间、日期进行处理。1、to_char()函数的用法1.1、将时间日
  • 在所有的比例中黄金分割是最能引起人的美感的,0.618被公认为最具有审美意义的比例数字。黄金分割之所以那么普遍的流行,我猜一定跟理想女人体的
  • 初学python,对python的对齐很重视,为了防止出错,使用spyder工具提供的功能下面是方法:1、首先打开Tools菜单栏下的Pre
  • 阅读上一篇:垂直栅格与渐进式行距(上) 新问题来也匆匆,去也“冲冲”。距上次发布垂直栅格与渐进式行距(上)发布,已经不知不觉过去了
  • alert table 表名 add column 列名 alter table 表名 drop column 列名 eg: alter t
  • Python 私有函数的实例详解与大多数语言一样,Python 也有私有的概念:• 私有函数不可以从它们的模块外面被调用• 私有类方法不能够
  •  在学习和使用各种数据库的过程中,我们常常会遇到聚族索引、非聚族索引、组合索引的概念,这些索引对我们使用数据库,特别是查询的速度的
  • 说到客户端数据存储,可能第一时间想到的是cookies,这是一种网站常见的存储数据的方法。它的最大优点是兼容性好,几乎所有浏览器都具有这个功
  • 代理模式的优点代理模式可以保护原对象,控制对原对象的访问;代理模式可以增强原对象的功能,通过代理对象来添加一些额外的功能;代理模式可以提高系
  • 利用 CSS 来实现对象的垂直居中有许多不同的方法,比较难的是选择那个正确的方法。我下面说明一下我看到的好的方法和怎么来创建一个好的居中网站
  • 我在程序中加入了分数显示,三种特殊食物,将贪吃蛇的游戏逻辑写到了SnakeGame的类中,而不是在Snake类中。特殊食物:1.绿色:普通,
手机版 网络编程 asp之家 www.aspxhome.com