通过函数将模块/函数集合转换为Python类 [英] Progammatically turn module/set of functions into a Python class

查看:117
本文介绍了通过函数将模块/函数集合转换为Python类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个具有束方法的文件为bunch_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?

我为什么要这样做呢?现在这是一个精神上的,学习练习,但我的具体使用心目中是采取的方法,并创建瓶子级别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

推荐答案

类型元类。使用类型生成类的格式如下:

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)

将它保存为bunch_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中的元类是什么?

这篇关于通过函数将模块/函数集合转换为Python类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆