了解类类型 '__main__.ClassName' [英] Understanding class type '__main__.ClassName'
问题描述
代码:
class Fraction(object):
def __init__(self, num, denom):
self.numerator = num
self.denominator = denom
def main():
f = Fraction(1, 3)
print type(f)
if __name__ == "__main__":
main()
输出:
<class '__main__.Fraction'>
问题:
- 为什么是
__main__.Fraction
而不是Fraction
类型? 为什么会有."
__main__
和Fraction
之间?."暗示Fraction
是__main__
的子类.但为什么?即使我从代码中删除If __name__ == "__main__"
,我仍然得到相同的输出:
- Why is the type
__main__.Fraction
instead of justFraction
? Why is there "." between
__main__
andFraction
? "." implies thatFraction
is a sub-class of__main__
. But why? Even if I removeIf __name__ == "__main__"
from the code, I still get the same output:
class Fraction(object):
def __init__(self, num, denom):
self.numerator = num
self.denominator = denom
f = Fraction(1,3)
print type(f)
output: <class '__main__.Fraction'>
推荐答案
由于您没有在类上定义
__repr__
(或__str__
),它是从超类继承的——object
代码> 以及它是如何写在那里的.因此,您所有的类实例都以这种方式表示.至于类本身,您需要更改元类上的__repr__
/__str__
,即我们所讨论的类是其实例的类;默认元类是type
.__main__
是模块的名称,这里当你直接执行它时,它被认为是一个 script 并且所有的脚本都有名称__main__
在 Python 中
As you have not defined a
__repr__
(or__str__
) on the class, it's inherited the one from the superclass --object
and that how its written there. So, all your class instances are expressed that way. As for the class itself, you need to change the__repr__
/__str__
on the metaclass i.e. the class of which our class in question is an instance of; the default metaclass istype
.__main__
is the name of the module, here as you are directly executing it, its being considered as a script and all scripts have the name__main__
in Python
中间有一个 .
因为 Fraction
是脚本 __main__
的一个属性,模块;并且属于模块级范围
There's a .
in between because Fraction
is an attribute of the script __main__
, the module; and belongs to the module level scope
<小时>
示例:
In [47]: class MyMeta(type):
...: def __repr__(cls):
...: return 'Whatever...'
...:
In [48]: class MyClass(metaclass=MyMeta):
...: def __repr__(self):
...: return 'Howdy...'
...:
In [49]: obj = MyClass()
In [50]: print(obj)
Howdy...
In [51]: print(type(obj))
Whatever...
对于Python2,需要将__metaclass__
定义为类属性.
For Python2, you need to define __metaclass__
as a class attribute.
这篇关于了解类类型 '__main__.ClassName'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!