簡體   English   中英

Python:如何正確調用另一個類的方法

[英]Python: how call a method of another class correctly

我有兩節課

check_input_types - 檢查輸入數據的類型Rules - 獲取一些數據

class check_input_types:

    def comparison_operator(op):
        if op == 'совпадает_с':
            return '=='
        elif op == 'не_равно':
            return '!='
        elif op == 'больше':
            return '>'
        elif op == 'меньше':
            return '<'
        else:
            raise Exception('Неверно введен оператор сравнения!')

    def check_input_type(input_type, element):
        if input_type == 'number':
            return int(element)
        elif input_type == 'string':
            return element

class Rules:

    def __init__(self, path):
        with open(path, 'r') as f:
            file = f.read()
        json_parser = Lark(grammar, parser='lalr', postlex=PythonIndenter(), start='if_any')
        if file.endswith('\n'):
            file = file[:-1]
        tree = json_parser.parse(file)

    code = []
    add_indent = ''



    def if_any(t):
        global code

        if t.data == "if_any":
            code.append("if any(")
            for i, child in enumerate(t.children):
                if child.data == "element":
                    comparison_element = check_input_type(child.children[0].data, child.children[0].children[0])
                elif child.data == "comparison":
                    code.append("{} {} x for x in".format(comparison_element, comparison_operator(child.children[0])))
                elif child.data == "array":
                    array = list(check_input_type(element.data, element.children[0][:]) \
                                 for element in child.children)
                    code.append(str(array))
                    code.append('):')
                elif child.data == 'result':
                    code.append("\n\tprint(str({}))".format(child.children[0].children[0]))

但是沒有調用一流的方法。 在二等艙中調用它的正確方法是什么?

首先,如果您需要使用類,則應按如下方式引用它:

cit = check_input_types()  # create instance
cit.comparison_operator ('совпадает_с') # call function from instance

但是,屬於類的非靜態函數的第一個變量不是外部傳遞的變量,而是對類本身的引用。 因此,通常將self作為第一個參數(但可以是任何名稱)。

您也可以從類別中刪除comparison_operatorcheck_input_type功能,然后打電話給他們,你是在規則類的方式。

PS:你需要在類Rules的函數中添加一個self,才不會出錯:

...
def is_any(self, t):
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM