PythonIC 用法或下划线(私有)名称 Python
Pythonic usage or underscore (private) names in Python
我想知道在模块、classes 和方法中使用 _ 来编写 python 代码的 pythonic 方法。
示例 1:
import threading as _threading
class Thread(_threading.Thread):
pass
对
from threading import Thread
class MyThread(Thread):
pass
在模块级别,在这样的方法中引入私有变量是否有意义:
def my_module_method():
_throw = foo + bar
return _throw
对
def my_module_method():
throw = foo + bar
return throw
我假设私有名称的最佳用法是防止 class 实例使用某些私有临时方法是否正确,例如:
class MyClass(object):
_my_internal = 0
def _do_not_use_me()
pass
这样 class 的最终用户就会知道不要直接在以下地方使用这些方法:
foo = MyClass._do_not_use_me()
bar = MyClass._my_internal
任何其他关于私有名称一般用法的建议将不胜感激。
请记住,Python 没有什么比“硬性规则”更多的约定了。除了一些例外,只要您保持一致并且您的代码易于理解,为您的变量添加任何您想要的前缀都没有错。
但是,如果您想遵循通用惯例,请继续阅读。
一般
由于 Python 没有像其他一些语言那样的访问修饰符(访问修饰符如 private
、public
、protected
等),_
前缀标记 classes 中不被外部访问的字段、方法等。它标志着私人使用。
考虑到这一点,让我们一个一个地看你的例子:
示例 1
首选方式是:
from threading import Thread
class MyThread(Thread):
pass
您还可以使用:
import threading
class MyThread(threading.Thread):
pass
但是你不应该 _
前缀导入模块。
示例 2
在一般情况下,您无权访问函数的内部变量。因此没有理由使用 _
。方法是这样的:
def my_module_method():
throw = foo + bar
return throw
我能想到的唯一例外是在嵌套函数的情况下,您可以在其中复制名称并避免歧义,您将使用 _
来区分变量:
def my_outer_method():
throw = foo + bar
def my_inner_method(_throw):
return _throw * 2
return my_inner_method(throw)
示例 3
是的,这就是您使用 _
前缀的确切原因。
my_class = MyClass()
foo = my_class._do_not_use_me()
bar = my_class._my_internal
这告诉 class 的消费者他们正在做不应该做的事情或不安全的事情。
我想知道在模块、classes 和方法中使用 _ 来编写 python 代码的 pythonic 方法。
示例 1:
import threading as _threading
class Thread(_threading.Thread):
pass
对
from threading import Thread
class MyThread(Thread):
pass
在模块级别,在这样的方法中引入私有变量是否有意义:
def my_module_method():
_throw = foo + bar
return _throw
对
def my_module_method():
throw = foo + bar
return throw
我假设私有名称的最佳用法是防止 class 实例使用某些私有临时方法是否正确,例如:
class MyClass(object):
_my_internal = 0
def _do_not_use_me()
pass
这样 class 的最终用户就会知道不要直接在以下地方使用这些方法:
foo = MyClass._do_not_use_me()
bar = MyClass._my_internal
任何其他关于私有名称一般用法的建议将不胜感激。
请记住,Python 没有什么比“硬性规则”更多的约定了。除了一些例外,只要您保持一致并且您的代码易于理解,为您的变量添加任何您想要的前缀都没有错。
但是,如果您想遵循通用惯例,请继续阅读。
一般
由于 Python 没有像其他一些语言那样的访问修饰符(访问修饰符如 private
、public
、protected
等),_
前缀标记 classes 中不被外部访问的字段、方法等。它标志着私人使用。
考虑到这一点,让我们一个一个地看你的例子:
示例 1
首选方式是:
from threading import Thread
class MyThread(Thread):
pass
您还可以使用:
import threading
class MyThread(threading.Thread):
pass
但是你不应该 _
前缀导入模块。
示例 2
在一般情况下,您无权访问函数的内部变量。因此没有理由使用 _
。方法是这样的:
def my_module_method():
throw = foo + bar
return throw
我能想到的唯一例外是在嵌套函数的情况下,您可以在其中复制名称并避免歧义,您将使用 _
来区分变量:
def my_outer_method():
throw = foo + bar
def my_inner_method(_throw):
return _throw * 2
return my_inner_method(throw)
示例 3
是的,这就是您使用 _
前缀的确切原因。
my_class = MyClass()
foo = my_class._do_not_use_me()
bar = my_class._my_internal
这告诉 class 的消费者他们正在做不应该做的事情或不安全的事情。