将其他文件中的函数添加到Python类

问题描述:

我在设置此设置时遇到了麻烦,主要是因为我不确定要解决此问题的实际目的。

I am having trouble with this setup mainly because I am not sure what I actually want in order to solve this problem.

这是设置

- main.py
- lib
  - __init__.py 
  - index.py
  - test.py

__ init __。py 有此代码

import os
for module in os.listdir(os.path.dirname(__file__)+"/."):
    if module == '__init__.py' or module[-3:] != '.py':
        continue
    __import__(module[:-3], locals(), globals())
del module

main.py 具有以下代码现在的

from lib.index import *
print User.__dict__

index.py 具有此代码

class User(object):
    def test(self):
        return "hi"
    pass

test.py 他的代码

class User(object):
    def tes2(self):
        return "hello"

当我成功执行 main.py 时从 index.py 打印方法 test ,但是我想做的就是找出一种方法在lib文件夹中创建一个文件,该文件中只有一个函数的格式为

When I execute main.py it successfully prints the method test from index.py but what I am trying to do is figure out a way where I can just create a file in the lib folder where that while has only one function in the format

class User(object):
    def newFunction(self):
       return abc

,此功能应自动用于我在main.py

and this function should automatically be available for me in main.py

我确信这不是一件难事,但老实说我不知道​​我想要什么(寻找解决方案),这使我无法研究解决方案。

I am sure that this is not a hard thing to do but I honestly don't know what I want (what to search for to solve this) which is preventing me from researching the solution.

您可以使用元类来自定义类的创建并添加在其他地方定义的函数:

You can use a metaclass to customize class creation and add functions defined elsewhere:

import types
import os
import os.path
import imp

class PluginMeta(type):
    def __new__(cls, name, bases, dct):
        modules = [imp.load_source(filename, os.path.join(dct['plugindir'], filename))
                    for filename in os.listdir(dct['plugindir']) if filename.endswith('.py')]
        for module in modules:
            for name in dir(module):
                function = getattr(module, name)
                if isinstance(function, types.FunctionType):
                    dct[function.__name__] = function
        return type.__new__(cls, name, bases, dct)


class User(object):
    __metaclass__ = PluginMeta
    plugindir = "path/to/the/plugindir"

    def foo(self):
        print "foo"

user = User()
print dir(user)

然后在插件文件中,仅创建函数而不是类:

Then in the plugin files, just create functions not classes:

def newFunction(self, abc):
    self.abc = abc
    return self.abc

元类会找到它们,将它们变成方法,并将它们附加到您的班级上。

And the metaclass will find them, turn them into methods, and attach them to your class.