is it possible to include a new method to existing object at instance initialization? [duplicate]

StackOverflow https://stackoverflow.com/questions/23591336

  •  20-07-2023
  •  | 
  •  

Frage

this is my attempt in python 3.4:

import imp

def my_example_function():
  print("my_example_function:")

class my_class:
  def __init__(self):
    module = imp.load_source(my_example_function, __file__)

my_class_instance = my_class()

result is:

Traceback (most recent call last):
  File "D:\Python34\test.py", line 10, in <module>
    my_class_instance = my_class()
  File "D:\Python34\test.py", line 8, in __init__
    module = imp.load_source(my_example_function, __file__)
  File "D:\python34\lib\imp.py", line 166, in load_source
    spec = util.spec_from_file_location(name, pathname, loader=loader)
  File "<frozen importlib._bootstrap>", line 932, in spec_from_file_location
  File "<frozen importlib._bootstrap>", line 1439, in is_package
AttributeError: 'function' object has no attribute 'rpartition'

It looks like some kind of internal error a bug in python itself.

War es hilfreich?

Lösung

the error says, that a 'function'-object has no attribute 'rpartition'. The only function object, you give to load_source is my_example_function but a name aka string is expected. And strings have a method called rpartition. So if you use load_source correctly, you won't get an error. But I cannot say, how, because I don't understand what you try to do.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top