【问题标题】:Why is an object not created when a method is called during the object's contruction?为什么在对象的构造过程中调用方法时没有创建对象?
【发布时间】:2020-07-03 02:02:10
【问题描述】:

给定类test,为什么不能通过调用它的方法之一和构造函数来实例化它?

class test:
    def __init__(self, a):
        self.a = a

    def print_a(self):
        print(self.a)

这是一个例子:

>>> obj = test("Hello").print_a()  # Prints the desired output.
Hello
>>> obj
>>> print(obj)  # But the object does not exist.
None
>>> obj = test("Hello")  # It obviously works when doing it separately. 
>>> obj
<__main__.test object at 0x7f537fea3940>
>>> obj.print_a()
Hello

为什么不能将方法调用与构造函数调用链接起来?

这是在python3 中实现的。

【问题讨论】:

  • objprint_a的返回值,没有return语句,所以返回None
  • obj = test("Hello").print_a() 中,obj 设置为打印的结果,即无。含义方法 print_a 返回 None。

标签: python python-3.x oop object


【解决方案1】:

您正在将 obj 分配给函数 print_a 的返回值(它是 None,因为它没有返回值)。实际的测试对象从未被存储,因此当您尝试打印它时不再在范围内。

【讨论】:

    猜你喜欢
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-25
    • 2017-04-06
    • 1970-01-01
    • 2011-05-18
    • 2020-11-01
    相关资源
    最近更新 更多