Pergunta

Can someone please explain why I get different output when I run the Python script below?

I don't understand why getattr(sys.modules['importme'], 'MyClass') does not print the custom __repr__() function defined in MyClass.

printtest.py

#!/usr/bin/env python
import sys

import importme

def main():
    # This line prints "<class 'importme.MyClass'>"
    m = getattr(sys.modules['importme'], sys.argv[1])
    # This line prints "<MyClass {'text':, 'number':0}>"
    #m = importme.MyClass()
    print(m)

if __name__ == '__main__':
    main()

importme.py

class MyClass(object):
    text = ''
    number = 0

    def __init__(self, text = '', number = 0):
        self.text = text
        self.number = number

    def __repr__(self):
        return "<MyClass {'text':%s, 'number':%d}>" % (self.text, self.number)
Foi útil?

Solução

In the first case, you fetch the class object of importme.MyClass, and the string you print is its repr, i.e. the repr of the class object.

In the second case, you create an instance of type MyClass, in which case, printing invokes your custom repr (__repr__ applies to the instance of the class).

By the way, since you first import importme, this

getattr(sys.modules['importme'], sys.argv[1])

is equivalent to this:

getattr(importme, sys.argv[1])

I'm guessing what you meant to do in the first case is this:

m = getattr(importme, sys.argv[1])()
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top