简体   繁体   English

Python 内置数据类型怎么可能具有具有相同数据类型的属性?

[英]How is it possible that a Python built-in data type can have attributes that have the same data type?

Obviously this cannot be done in Python code, such as显然这在 Python 代码中是做不到的,比如

class Foo:
    a = Foo()

but how did they manage to program this when creating the language itself?但是在创建语言本身时,他们是如何进行编程的呢?

Examples include int having the attributes real , imag , numerator and denominator ;示例包括具有属性realimagnumeratordenominatorint str having __doc__ ; str__doc__ methods having their own methods and type being its own meta class.具有自己的方法和type的方法是自己的元 class。

How could they get around the recursion caused if you tried to replicate something like this using Python code?如果您尝试使用 Python 代码复制类似的内容,他们如何解决递归问题?

Well, your assumption is not exactly true.好吧,你的假设并不完全正确。 You can assign to class members after the class has been created.在创建 class 后,您可以分配给 class 成员。 Consider the following:考虑以下:

# Class definition
class Foo:

    foo = None

    def the_foo(self):
        return Foo.foo

# Assigning to the class member
Foo.foo = Foo()

# Creating an object and accessing class member through an object method
a_foo = Foo()
print("type(a_foo.the_foo()) =", type(a_foo.the_foo()))

This yields:这产生:

type(a_foo.the_foo()) = <class '__main__.Foo'>

So, if this can be done in Python, why not in built-in classes?那么,如果这可以在 Python 中完成,为什么不能在内置类中完成呢?

Not sure if this is along the lines of what you need to achieve.不确定这是否符合您需要实现的目标。
But a neat workaround might be to use @property decorators?但是一个巧妙的解决方法可能是使用@property装饰器?

class Foo:

    @property
    def a(self):
        return Foo()

x = Foo()
print(x)
print(x.a)
print(type(x) == type(x.a) == Foo)


<__main__.Foo object at 0x033083B8>
<__main__.Foo object at 0x033081D8>
True

Technically this gets you around the recursion.从技术上讲,这可以让你绕过递归。 It strictly speaking won't create the second instance immediately, so if that's a factor you need to take into consideration neither mine or Amitai's answers will do that for you.严格来说,它不会立即创建第二个实例,所以如果这是您需要考虑的一个因素,我的或 Amitai 的答案都不会为您做到这一点。 But it will create a property on instance creation called a but won't do anything until you access it.但它会在实例创建时创建一个名为a的属性,但在您访问它之前不会做任何事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM