繁体   English   中英

为什么在对象的构造过程中调用方法时未创建对象?

[英]Why is an object not created when a method is called during the object's contruction?

鉴于类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中实现的。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM