首页 > 解决方案 > 类方法:在函数中使用函数

问题描述

我有一种情况,我正在使用@classmethod为类创建构造函数。在这个构造函数中,一个函数被调用,然后又调用另一个函数。但要么这不起作用,要么(更有可能)我正在做一些事情让它不起作用。这是一个缩影的例子:

class testclass:
    def __init__(self, x):
        self.x = x

    @classmethod
    def constructor(cls, x):
        adj_x = cls.outer_adjust(cls, x)
        return testclass(adj_x)

    def outer_adjust(self, x):
        return self.inner_adjust(x)

    def inner_adjust(self, x):
        return x + 1

test_instance = testclass.constructor(4)

这会产生一条错误消息:

inner_adjust() missing 1 required positional argument: 'x'

我可以通过明确地将 self 传递给它来使其工作inner_adjust,例如

def outer_adjust(self, x):
    return self.inner_adjust(self, x)

但这意味着该outer_adjust方法不能在 之外使用constructor,这不是我想要的。

感激地接受任何帮助。

这是一个更详细的示例,显示了两个构造函数。我正在尝试遵循 什么是在 Python 中拥有多个构造函数的干净、pythonic 方式中描述的构造函数方法? 这本质上是构造函数进行一些处理来确定在实例化类时应该将哪些变量传递给init 。两个构造函数都给出相同的错误:

if_char_is_z_make_it_a() missing 1 required positional argument: 'char_input'

和以前一样,我需要能够在构造函数之外使用 if_char_is_make_it_a 函数(即,在正常使用类时)。

class testclass:
    def __init__(self, char):
        self.char = char

    @classmethod
    def constructor_from_int(cls, int_input):
        as_char = chr(int_input)
        char = cls.process_char(cls, as_char)
        return testclass(char)

    @classmethod
    def constructor_from_char(cls, char_input):
        char = cls.process_char(cls, char_input)
        return testclass(char)

    def process_char(self, char_input):
        processed_char = '(' + char_input + ')'
        output_char = self.if_char_is_z_make_it_a(processed_char)
        return output_char

    def if_char_is_z_make_it_a(self, char_input):
        if char_input == '(z)':
            return '(a)'
        return char_input

test_instance = testclass.constructor_from_char('a')

标签: python

解决方案


当您调用cls.outer_adjust时,constructor您正在调用未绑定的outer_adjust方法。

因此,您将类本身作为self而不是实例传递给期望接收实例作为参数的方法。

虽然,没有真正的理由有一个constructor方法。这正是__init__它的用途。

class testclass:
    def __init__(self, x):
        self.x = self.outer_adjust(x)

    def outer_adjust(self, x):
        return self.inner_adjust(x)

    def inner_adjust(self, x):
        return x + 1

test_instance = testclass(4)

如果您绝对需要在实例化之前x完成转换,请改用。虽然,这通常不是必需的。__new__

多个构造函数

如果由于某种原因您仍然需要一个constructor方法,例如如果您想要多个构造函数。然后请记住,outer_adjustandinner_adjust是实例方法,这意味着必须在创建实例后调用它们。

class testclass:
    def __init__(self, x):
        self.x = x

    @classmethod
    def constructor1(cls, x):
        instance = cls(x)
        instance.outer_adjust()
        return instance

    @classmethod
    def constructor2(cls, x):
        instance = cls(x)
        instance.inner_adjust()
        return instance

    def outer_adjust(self):
        print('Do something else')
        return self.inner_adjust()

    def inner_adjust(self):
        self.x += 1

作为旁注,请注意我不需要调用testclass,而是简单地cls在构造函数方法中调用。由于这是一个类方法,我们不需要显式命名该类。这更好,特别是如果您要使用继承。


推荐阅读