如何正确调用另一个类的方法?附输入类型检查类示例
嘿,我来帮你梳理下怎么在Python里调用另一个类的方法,结合你给出的check_input_types类来具体说明~
首先先提个小建议:你写的comparison_operator和check_input_type方法都没有self参数,这类不需要依赖实例状态的方法,最好加上@staticmethod装饰器,这样代码更规范,可读性也更强。修改后的check_input_types类如下:
class check_input_types: @staticmethod def comparison_operator(op): if op == 'совпадает_с': return '==' elif op == 'не_равно': return '!=' elif op == 'больше': return '>' elif op == 'меньше': return '<' else: raise Exception('Неверно введен оператор сравнения!') @staticmethod def check_input_type(input_type, element): if input_type == 'number': return int(element) elif input_type == 'string': return element
接下来分两种常见场景讲调用方式:
1. 在类外部直接调用
因为这两个是静态方法,不需要创建类的实例,直接通过**类名.方法名()**就能调用:
# 调用comparison_operator获取比较符号 op_symbol = check_input_types.comparison_operator('больше') print(op_symbol) # 输出:> # 调用check_input_type转换输入类型 processed_num = check_input_types.check_input_type('number', '789') print(processed_num, type(processed_num)) # 输出:789 <class 'int'>
2. 在Rules类内部调用
如果你的Rules类需要用到check_input_types的方法,同样直接通过类名调用即可,举个示例:
class Rules: def filter_data(self, op_str, input_type, element, target_list): # 先调用check_input_types的方法处理输入 operator = check_input_types.comparison_operator(op_str) processed_element = check_input_types.check_input_type(input_type, element) # 这里写你的业务逻辑,比如根据操作符筛选数据 filtered_result = [] for item in target_list: if eval(f"{item} {operator} {processed_element}"): filtered_result.append(item) return filtered_result # 测试调用 rules = Rules() test_list = [10, 20, 30, 40] result = rules.filter_data('меньше', 'number', '30', test_list) print(result) # 输出:[10, 20]
补充:如果是实例方法的情况
要是你的类方法是依赖实例状态的(带self参数的实例方法),那调用前需要先创建类的实例:
# 假设check_input_types是实例方法的写法 class check_input_types: def comparison_operator(self, op): # 逻辑不变... def check_input_type(self, input_type, element): # 逻辑不变... # 外部调用 checker = check_input_types() op_symbol = checker.comparison_operator('не_равно') # 在Rules类里调用 class Rules: def get_data(self, op_str): checker = check_input_types() return checker.comparison_operator(op_str)
总结一下核心逻辑:
- 静态方法/类方法:直接用
类名.方法名()调用,无需实例化 - 实例方法:先创建类的实例
obj = 类名(),再用obj.方法名()调用
内容的提问来源于stack exchange,提问作者Petr Petrov
相关产品推荐
相关产品推荐

