简体   繁体   中英

Creation of a class instance by reflection in Python does not work

I have the following code:

theModule = locate(<the location of my python script in the file system>)
class_ = getattr(theModule, '<the class of my module>')
myAppli = class_()

But I always have an AttributeError exception when trying to perform the "getattr" method.

My objective was to create a Python class from a file somewhere in the file system, and execute methods on it by reflection without using the class declaration in the Python code.

Example

For example, I have the following python script, let's say that the name of the script file is: myScript.py

import sys

class PythonAppli:
  def aMethod(self):
    sys.echo('I am here\n')

And I perform this in another script in the same directory:

from pydoc import locate

theModule = locate('myScript.py')
class_ = getattr(theModule, 'pythonAppli')
myAppli = class_()

I have the following exception on the "getattr" line:

AttributeError: class PythonAppli has no attribute 'pythonAppli'

Note that if I add this line before my "getattr" method call:

inspect.getmembers(theModule)

I find 'pythonAppli' in the list of attributes.

I looked on the question about dynamic instanciation on StackOverflow but could not find my error here.

Per MisterMiyagi answer, my mistake was theModule was already my desired class. The following code did work:

from pydoc import locate

theModule = locate('myScript.py')
pythonAppli = theModule()

So it was much more simple that I imagined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM