如何访问与Python中的函数参数相同的全局名称
我正在尝试编写一个模块,该模块具有与numpy类似的接口以及一个数据类型模拟。在numpy中,dtype是类的名称,也是各种函数的参数。我希望能够编写接受参数dtype的函数,但也能够创建类dtype的对象 在下面的示例中,我尝试创建一个数字类,该类是使用dtype参数创建的,该参数可以是dtype类型的对象,也可以是可以传递给dtype构造函数的其他对象如何访问与Python中的函数参数相同的全局名称,python,numpy,Python,Numpy,我正在尝试编写一个模块,该模块具有与numpy类似的接口以及一个数据类型模拟。在numpy中,dtype是类的名称,也是各种函数的参数。我希望能够编写接受参数dtype的函数,但也能够创建类dtype的对象 在下面的示例中,我尝试创建一个数字类,该类是使用dtype参数创建的,该参数可以是dtype类型的对象,也可以是可以传递给dtype构造函数的其他对象 class dtype(): def __init__(self, width=1): self.width = w
class dtype():
def __init__(self, width=1):
self.width = width
class number():
def __init__(self, value, dtype=None):
self.value = value
dtype_ = dtype
global dtype
if isinstance(dtype_, dtype):
self.dtype = dtype_
elif dtype_ is None:
self.dtype = dtype()
else:
self.dtype = dtype(dtype_)
def __repr__(self):
return 'number(value={},width={})'.format(self.value, self.dtype.width)
v1 = number(1)
t2 = dtype(2)
v2 = number(1, t2)
v3 = number(1, 3)
这不起作用:
global dtype
^
SyntaxError: name 'dtype' is parameter and global
有没有一种方法可以实现我在Python中试图实现的功能,或者说NumPy之所以能够做到这一点,仅仅是因为它是用C编写的?在像NumPy这样的大型库中,通常情况是在包的不同子模块中实现不同的功能,而且不会出现全局/局部名称冲突,因为大多数希望将名称用作参数名称的函数都位于不同的子模块中,而该名称用作全局名称。下面是一个玩具示例:
# mypackage/__init__.py
from .a import thing
from .b import thing_user
# mypackage/a.py
class thing:
...
# mypackage/b.py
from . import a
def thing_user(thing):
do_something_with(thing) # the argument
do_something_with(a.thing) # the class
...
NumPy也自动避免了用C编写的部分中的问题,但这就是为什么用Python编写的部分可以有名为dtype的参数而没有问题-dtype不是全局变量
如果要使用单个文件,最简单的选择是使用辅助全局文件以避免名称冲突,只要不需要支持重新指定或模拟全局文件:
class thing:
...
_thing = thing
def thing_user(thing):
do_something_with(thing) # the argument
do_something_with(_thing) # the class
如果这不适合您的用例,您可以让函数通过直接访问其模块的globals dict或使用助手函数来访问本地变量隐藏的全局变量:
class thing:
...
def _get_thing():
return thing
def thing_user(thing):
do_something_with(thing) # the argument
do_something_with(globals()['thing']) # the class
do_something_with(_get_thing()) # the class again
调用与类相同的参数并对其进行隐藏背后有什么原因吗?调用param dtypeparam,您就是金色的。不太清楚为什么会如此激烈dv@PatrickArtner:调用它dtypeparam会使按关键字方式传递参数变得更加笨拙。我知道如果我不得不写numpy.array[1,2,3],dtypeparam='int64',我会讨厌它。我想知道为什么这个问题吸引了这么多的反对票…谢谢。我现在对解决方法很满意,并最终制作了一个文件范围引用_dtype_class=dtype,它让我可以做我想做的事情。