python 内置方法是否可以在任何地方的替代命名空间中使用?

发布于 2024-10-10 05:35:37 字数 1096 浏览 4 评论 0原文

python 内置方法是否可在包中引用某处?

让我解释一下。在我早期使用 python 的时候,我制作了一个与此类似的 django 模型:

class MyModel(models.Model):
    first_name = models.CharField(max_length=100, null=True, blank=True)
    last_name = models.CharField(max_length=100, null=True, blank=True)
    property = models.ForeignKey("Property")

此后我需要向它添加一个属性。这给我留下了这个模型:

class MyModel(models.Model):
    first_name = models.CharField(max_length=100, null=True, blank=True)
    last_name = models.CharField(max_length=100, null=True, blank=True)
    property = models.ForeignKey("Property")

    @property
    def name(self):
        return "{} {}".format(first_name, last_name)

所以现在在运行时我收到错误:TypeError: 'ForeignKey' object is not callable。发生这种情况是因为属性的ForeignKey 已替换了内置标识符属性。我希望能够做的是,使用 @sys.property (或类似的东西)而不是 @property

注意:我已经知道将 name 属性移动到属性字段声明上方的解决方法。我不太关心这个特殊情况,因为我主要问题是引用 python 内置函数的替代位置。

Are the python built-in methods available to reference in a package somewhere?

Let me explain. In my early(ier) days of python I made a django model similar to this:

class MyModel(models.Model):
    first_name = models.CharField(max_length=100, null=True, blank=True)
    last_name = models.CharField(max_length=100, null=True, blank=True)
    property = models.ForeignKey("Property")

I have since needed to add a property to it. This leaves me with this model:

class MyModel(models.Model):
    first_name = models.CharField(max_length=100, null=True, blank=True)
    last_name = models.CharField(max_length=100, null=True, blank=True)
    property = models.ForeignKey("Property")

    @property
    def name(self):
        return "{} {}".format(first_name, last_name)

So now at runtime I get the error: TypeError: 'ForeignKey' object is not callable. This is happening because the ForeignKey for property has replaced the built-in identifier property. What I would like to be able to do is, instead of @property use @sys.property (or something similar).

Note: I already know about the workaround of moving the name property above the declaration of the property field. I am not so concerned about this particular case as I am the main question of alternative locations for referencing the python built-ins.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦回梦里 2024-10-17 05:35:37

使用内置,或__builtin__ 如果您使用的是 Python 2。

def open():
    pass

import __builtin__

print open
print __builtin__.open

这将为您提供:

<function open at 0x011E8670>
<built-in function open>

Use builtins, or __builtin__ if you're on Python 2.

def open():
    pass

import __builtin__

print open
print __builtin__.open

This gives you:

<function open at 0x011E8670>
<built-in function open>
陈独秀 2024-10-17 05:35:37

Python 有一个 builtins 模块,其中“真正的全局” “ 事物——通常只是存储标准内置函数和类型。在 Python 2 中,它被命名为 __builtin__ ,但工作原理基本相同。

该模块可以像任何其他模块一样导入,但它也神奇地为每个其他模块提供内置名称(不会隐藏它们)。


如果您想知道它是如何工作的,builtins 文档说:

作为实现细节,大多数模块都将名称 __builtins__ 作为其全局变量的一部分提供。 __builtins__ 的值通常是该模块或该模块的 __dict__ 属性的值。由于这是一个实现细节,因此 Python 的替代实现可能不会使用它。

并且 exec 说:

如果globals字典不包含键__builtins__的值,则对内置模块builtins字典的引用插入到该键下。这样,您可以通过在将您自己的 __builtins__ 字典传递给 exec() 之前将其插入到全局变量中来控制所执行的代码可以使用哪些内置函数。

因此,至少在 CPython 中,当您计算 abs 时,它会在 globals()['abs'] 中查找,但在那里找不到,然后在 >globals()['__builtins__'].__dict__['abs']

每当 Python(或至少 CPython)创建一个新的模块对象时,它的代码都会针对带有 empty __builtins__globals 执行,这意味着默认的 builtins 模块值被填充,这样就可以工作了。这个 globals 是为模块中定义的每个函数和类复制的(以及您使用 globals 显式执行的任何操作,而不显式替换 __builtins__ >),所以它也可以在函数和类中工作。

Python has a builtins module where "truly global" things—normally just the standard builtin functions and types—are stored. In Python 2, it was named __builtin__, but worked mostly the same.

This module can be imported just like any other module—but it also magically supplies the builtin names for every other module (that doesn't hide them).


If you're wondering how that works, the builtins docs say:

As an implementation detail, most modules have the name __builtins__ made available as part of their globals. The value of __builtins__ is normally either this module or the value of this module’s __dict__ attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.

And exec says:

If the globals dictionary does not contain a value for the key __builtins__, a reference to the dictionary of the built-in module builtins is inserted under that key. That way you can control what builtins are available to the executed code by inserting your own __builtins__ dictionary into globals before passing it to exec().

So, at least in CPython, when you evaluate abs, it's looked up in globals()['abs'], not found there, and then looked up in globals()['__builtins__'].__dict__['abs'].

And whenever Python (or at least CPython) creates a new module object, its code is executed against a globals with an empty __builtins__, which means the default builtins module value gets filled in, so that works. And this globals is the one that gets copied for very function and class defined in the module (and anything you do explicitly with globals without explicitly replacing __builtins__), so it works inside functions and classes as well.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文