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)
In the first case, you fetch the class object of
importme.MyClass
, and the string you print is itsrepr
, i.e. therepr
of the class object.In the second case, you create an instance of type
MyClass
, in which case, printing invokes your customrepr
(__repr__
applies to the instance of the class).By the way, since you first
import importme
, thisis equivalent to this:
I'm guessing what you meant to do in the first case is this: