【问题标题】:Import Python class that only has `__new__` into Robot Framework将只有 `__new__` 的 Python 类导入 Robot Framework
【发布时间】:2019-05-31 04:56:45
【问题描述】:

在 Robot Framework 中导入一个 python 类,如下所示:

Python: MyClass.py

class MyClass:
    def __new__(cls, a, b):
        # implementation here

机器人框架: MyTest.robot

*** Settings ***
Library    MyClass.py    a=1    b=2

收到错误Error in file 'MyTest.robot': Test Library 'MyClass' expected 0 arguments, got 2.

我了解该错误是因为 MyClass 没有定义 __init__(如果已定义,则没有导入错误)。

我的问题是:如何导入MyClass.py,它定义了__new__,但没有定义__init__

(不详细说明为什么我有__new__ 而不是__init__

【问题讨论】:

  • MyClass 是你自己实现的类吗?
  • @gachdavit 是的,然后导入到 Robot Framework 中。
  • 这听起来像xy problem。为什么你不愿意创建一个带有两个参数的__init__ 方法?

标签: robotframework


【解决方案1】:

根据python documentation__new__ 会将它收到的参数传递给__init__。由于您没有创建接受参数的 __init__,这就是您收到错误的原因。

如果__new__()返回一个cls的实例,那么新实例的__init__()方法将像__init__(self[, ...])一样被调用,其中self是新实例其余参数与传递的相同到__new__()

如果您不想调用 __init__,您可能会从这个问题中获得一些帮助:Possible to prevent init from being called?

【讨论】:

  • 我明白了。你和@gachdavit 都在说同样的话。我添加了def __init__(self, *args, **kwargs): pass,现在它正在工作。发送!
【解决方案2】:

__new__ 负责实例创建,__init__ 只是实例创建后的初始化器。首先总是被称为__new__,然后是__init____new__ 始终默认为 @staticmethod,但您也可以使用 @staticmethod 装饰器(相同)。

class Foo:

    @staticmethod
    def __new__(cls):
        print('Foo.__new__ is called')
        obj = super().__new__(cls)
        print(obj) # <__main__.Foo object at 0x7f82c1403588> This is "f" object.
        return obj

    def __init__(self, *args, **kwargs):
        print('Foo.__init__ is called !!!')

f = Foo()

希望对你有帮助。

【讨论】:

  • Tx,但这解释了 __new____init__ 的属性,但没有解释如何在 Robot Framework 中导入该类。
  • 不客气。 __new__ 不影响导入。我认为您在实例创建过程中遇到了问题。究竟哪个类不能从 Robot 框架中导入?
猜你喜欢
  • 2015-11-12
  • 2019-04-21
  • 2018-11-25
  • 2014-03-23
  • 2016-02-16
  • 1970-01-01
  • 2021-06-24
  • 2015-01-06
  • 1970-01-01
相关资源
最近更新 更多