了解类类型 '__main__.ClassName' [英] Understanding class type '__main__.ClassName'

查看:49
本文介绍了了解类类型 '__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'>

问题:

  1. 为什么是 __main__.Fraction 而不是 Fraction 类型?
  2. 为什么会有."__main__Fraction 之间?."暗示 Fraction__main__ 的子类.但为什么?即使我从代码中删除 If __name__ == "__main__",我仍然得到相同的输出:

  1. Why is the type __main__.Fraction instead of just Fraction?
  2. Why is there "." between __main__ and Fraction? "." implies that Fraction is a sub-class of __main__. But why? Even if I remove If __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'>

推荐答案

  1. 由于您没有在类上定义 __repr__(或 __str__),它是从超类继承的——object代码> 以及它是如何写在那里的.因此,您所有的类实例都以这种方式表示.至于类本身,您需要更改元类上的 __repr__/__str__ ,即我们所讨论的类是其实例的类;默认元类是 type.__main__ 是模块的名称,这里当你直接执行它时,它被认为是一个 script 并且所有的脚本都有名称 __main__在 Python 中

  1. 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 is type. __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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆