相关疑难解决方法(0)

为什么python实例没有__name__属性?

>>> class Foo:
...   'it is a example'
...   print 'i am here'
... 
i am here
>>> Foo.__name__
'Foo'
>>> Foo().__name__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Foo instance has no attribute '__name__'
>>> Foo.__doc__
'it is a example'
>>> Foo().__doc__
'it is a example'
>>> Foo.__dict__
{'__module__': '__main__', '__doc__': 'it is a example'}
>>> Foo().__dict__
{}
>>> Foo.__module__
'__main__'
>>> Foo().__module__
'__main__'
>>> myname=Foo()
>>> myname.__name__
Traceback (most recent call last):
 File …
Run Code Online (Sandbox Code Playgroud)

python

17
推荐指数
1
解决办法
1万
查看次数

以声明方式设置类__name__

为什么不能以声明方式覆盖类名,例如使用不是有效标识符的类名?

>>> class Potato:
...     __name__ = 'not Potato'
...     
>>> Potato.__name__  # doesn't stick
'Potato'
>>> Potato().__name__  # .. but it's in the dict
'not Potato'
Run Code Online (Sandbox Code Playgroud)

我想也许这只是在类定义块完成后被覆盖的情况.但似乎这不是真的,因为名称是可写的,但显然没有在类dict中设置:

>>> Potato.__name__ = 'no really, not Potato'
>>> Potato.__name__  # works
'no really, not Potato'
>>> Potato().__name__  # but instances resolve it somewhere else
'not Potato'
>>> Potato.__dict__
mappingproxy({'__module__': '__main__',
              '__name__': 'not Potato',  # <--- setattr didn't change that
              '__dict__': <attribute '__dict__' of 'no really, not Potato' objects>,
              '__weakref__': <attribute …
Run Code Online (Sandbox Code Playgroud)

python metaclass python-datamodel python-descriptors python-object

6
推荐指数
1
解决办法
586
查看次数

当类型(n).__ name__有效时,为什么n .__ name__属性错误?

n = 20
print n.__name__
Run Code Online (Sandbox Code Playgroud)

我收到错误,因为n没有属性__name__:

AttributeError: 'int' object has no attribute '__name__'
Run Code Online (Sandbox Code Playgroud)

但是nint类的一个实例,并int.__name__给出了结果,那么为什么会n.__name__抛出错误.我期望因为n是一个类的实例int,它应该可以访问该类的所有属性.

python attributes class instance

4
推荐指数
1
解决办法
255
查看次数