python - 类方法:在函数中使用函数
问题描述
我有一种情况,我正在使用@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')
解决方案
当您调用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_adjust
andinner_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
在构造函数方法中调用。由于这是一个类方法,我们不需要显式命名该类。这更好,特别是如果您要使用继承。
推荐阅读
- eclipse - 尝试启动我的 javaFX 应用程序时出现错误:“缺少 JavaFX 运行时组件,需要运行此应用程序”
- r - Displaced line connecting average points using plot() and lines() in R
- r - 如何在短时间内计算一个数据集中的经纬度点与另一个数据集中的经纬度点之间的最短距离
- javascript - 我循环浏览一系列音频文件的方法是否有错误?
- r - 如何提取列表列表中所有列表的行名并将它们存储在新数据框或列表列表中
- android - HereMaps SDK V3.10.x 出现 NullPointerException
- protractor - 使用allowAnimations时未定义获取角度
- c++ - QProcess 和 QLocalSocket - 没有收到 IPC 消息
- django - 如何在编辑时更改表单值?
- apache - 是否可以在每个 API Respurce 级别上在 Apache Web 2.4 中启用相互 SSL?