Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

python - Understanding class type '__main__.ClassName'

Code:

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()

Output:

<class '__main__.Fraction'>

Question:

  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'>
    
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  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

  2. There's a . in between because Fraction is an attribute of the script __main__, the module; and belongs to the module level scope


Example:

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...

For Python2, you need to define __metaclass__ as a class attribute.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...