打印时未调用__str__方法

时间:2017-08-26 08:38:23

标签: python class

我试图创建一个简单的sql构建器类,但是当我尝试打印import_的输出时,它似乎没有返回get_sql的内容,即使它在__str__中{1}}功能。我做错了什么?

class Query(object):
    """
    Query builder entry functions
    """
    @classmethod
    def _builder(cls):
        return QueryBuilder()

    @classmethod
    def import_(cls, source_type):
        return cls._builder().import_(source_type)


class QueryBuilder(object):
    """
    Query Builder is the main class that generates sql
    """
    def __init__(self, quote_char='"'):
        self._from = []
        self._import = None
        self._source_type = None
        self.quote_char = quote_char

    def import_(self, source_type):
        if source_type == SourceType.XML:
            raise KeyError('Importing a XML is not supported')
        self._source_type = source_type

    def __str__(self):
        return self.get_sql(quote_char='"')

    def get_sql(self):
        if not (self._import):
            return 'test'
        return 'e'

打印脚本:

importQuery = Query.import_(sourceTypeEnum)
print(importQuery)

1 个答案:

答案 0 :(得分:1)

您需要在return self方法的末尾添加QueryBuilder.import_,否则它将返回None,因此您的importQuery将为None - 不是您预期的QueryBuilder实例。