![](/img/trans.png)
[英]python can't set attributes of built-in/extension type 'object'
[英]How is it possible that a Python built-in data type can have attributes that have the same data type?
显然这在 Python 代码中是做不到的,比如
class Foo:
a = Foo()
但是在创建语言本身时,他们是如何进行编程的呢?
示例包括具有属性real
、 imag
、 numerator
和denominator
的int
; str
有__doc__
; 具有自己的方法和type
的方法是自己的元 class。
如果您尝试使用 Python 代码复制类似的内容,他们如何解决递归问题?
好吧,你的假设并不完全正确。 在创建 class 后,您可以分配给 class 成员。 考虑以下:
# 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()))
这产生:
type(a_foo.the_foo()) = <class '__main__.Foo'>
那么,如果这可以在 Python 中完成,为什么不能在内置类中完成呢?
不确定这是否符合您需要实现的目标。
但是一个巧妙的解决方法可能是使用@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
从技术上讲,这可以让你绕过递归。 严格来说,它不会立即创建第二个实例,所以如果这是您需要考虑的一个因素,我的或 Amitai 的答案都不会为您做到这一点。 但它会在实例创建时创建一个名为a
的属性,但在您访问它之前不会做任何事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.