【发布时间】: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 中实现的。
【问题讨论】:
-
obj是print_a的返回值,没有return语句,所以返回None。 -
在
obj = test("Hello").print_a()中,obj 设置为打印的结果,即无。含义方法 print_a 返回 None。
标签: python python-3.x oop object