Python中使用对象的点符号

时间:2019-03-13 17:48:34

标签: python-3.x

一个点符号怎么容易?例如,模拟ArgumentParser的结果时。我已经开始执行以下操作:

class ArbitraryObject:
    pass

foo = ArbitraryObject()
foo.dot = "dot notation works!"
foo.w00t = '!'

但是我不想为此创建一个自定义类,因为这些最终会到处乱码。我宁愿直接使用object,但这会导致此错误:

>>> example_for_so = object()
>>> example_for_so.fail = "this should work, right?"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'fail'
>>> 

所以问题:

  • 有更简单的方法吗?
  • 是否经常使用这种点符号?

为澄清起见进行编辑:

说正常代码如下:

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Example for S/O")
    parser.add_argument("filename", type=str, help="Output file")
    args = parser.parse_args()

    complicated_object = ComplicatedClass(args)
    complicated_object.calculate()

然后我想要一个测试ComplicatedClass的测试:

def test_using_attrdict():
    # Arrange
    input = attrdict.AttrDict({"filename": "sample_file.yml"})

    # Act
    complicated_object = ComplicatedClass(input)
    complicated_object.calculate()

def test_using_dot_notation():
    # Arrange
    input = ArbitraryObject()
    input.filename = "sample_file.yml"

    # Act
    complicated_object = ComplicatedClass(input)
    complicated_object.calculate()

0 个答案:

没有答案