问题描述
假设我有一个文件,其中包含一堆方法,如bunk_methods.py:
Suppose I have a file with a bunch methods as bunch_methods.py:
def one(x):
return int(x)
def two(y)
return str(y)
是否有一种方法可以通过整体导入模块或选择方法来采用那组方法,然后将导入的方法转换为类?
Is there a way to take that group of methods by importing the module whole or select methods, and turn the imported into a class?
例如伪明智的
def make_class_from_module(which_module_or_listing_of_methods):
class = turn_module_to_class(which_module_or_listing_of_methods)
return class
如此
BunchClass = make_class_from_module(bunch_methods)
BunchClass = make_class_from_module(bunch_methods)
在我的脑海中听起来很合法,但是它可行吗?如果应该,我将如何开始做这样的事情?或者我有什么选择?
Sounds legit in my mind, but how viable is it? How would I begin to do something like this, if I should even, or what are my alternatives?
我为什么要这样做?目前,这是一种精神与心理上的交流.学习练习,但我要记住的具体用途是采用方法并创建 flask-classy FlaskView类.我想潜在地使用各种方法,并可能使用&通过FlaskView在不同的上下文中重复使用它们
Why would I want to do this? Right now it is a mental & learning exercise, but my specific use in mind is take methods and create flask-classy FlaskView classes. I'd like to potentially take a grab bag of methods and potentially use & reuse them in differing contexts with FlaskView
推荐答案
您还可以使用type
元类解决此问题.使用type
生成类的格式如下:
You can also solve this problem using the type
meta-class. The format for using type
to generate a class is as follows:
type(name of the class,
tuple of the parent class (for inheritance, can be empty),
dictionary containing attributes names and values)
首先,我们需要重新处理您的函数,以将类作为第一个属性.
First, we need to rework your functions to take a class as the first attribute.
def one(cls, x):
return int(x)
def two(cls, y):
return str(y)
将其另存为bundle_method.py,现在我们可以按以下方式构造我们的类了.
Save this as bunch_method.py, and now we can construct our class as follows.
>>> import bunch_methods as bm
>>> Bunch_Class = type('Bunch_Class', (), bm.__dict__)
>>> bunch_object = Bunch_Class()
>>> bunch_object.__class__
<class '__main__.Bunch_Class'>
>>> bunch_object.one(1)
1
>>> bunch_object.two(1)
'1'
有关元类的出色(且很长)指南,请参见以下文章. 什么是Python中的元类?
See the following post for a excellent (and long) guide on meta-classes. What is a metaclass in Python?
这篇关于以编程方式将模块/函数集转换为Python类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!