python - Python 中的递归类定义

标签 python class recursion fluent-interface python-2.x

我正在尝试使用 Python 中的流畅接口(interface)。

流利的 sql 查询生成器的示例在使用中看起来像这样:

sql.select('foo').select('bar').from('sometable').tostring() 

我很快意识到递归定义嵌套类的能力可能会有所帮助。

class sql:
    class select:        
        class select   # <--  HERE
        def __init__(self, dbcolumn, astype=None, asname=None):
            self.dbcolumn = dbcolumn
            self.astype = astype
            self.asname = asname

在注释'# <-- HERE' 标记的行中:
我希望此嵌套类引用引用包含类的相同“选择”类定义。

这有可能吗?可能使用了一些我不知道的关键字?

最佳答案

不需要“递归类定义”。要允许链接,您需要做的就是在您的方法中返回 self(如果您的对象不可变或某些方法不应修改输入对象,则返回同一类的实例)。

例子:

>>> class SQL(object):
...     def __init__(self):
...         self.columns = []
...     def select(self, col):
...         self.columns.append(col)
...         return self
...
>>> s = SQL()
>>> s.select('foo').select('bar').columns
['foo', 'bar']

关于python - Python 中的递归类定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11645680/

相关文章:

c++ - 递归定义数组中的数据对齐和排序

python - 索引错误: list index out of range when assigning values to tuples from a for loop

python - 如何在基于类的 View 中编写自己的方法并调用 url 中的方法

python - 在 python 中模拟一个类

python - Django related_table() 和 extra()

java - ArrayList递归不考虑重复元素

class - 同一元素中的两个框阴影没有逗号分隔

python - Python 中的实例变量与类变量

c# - C#如何制作行为类似于Nullable <T>的类

python - 大列表的最大递归