简体   繁体   中英

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

Given the class test , why it is not possible to instantiate it by calling one of its methods along with the constructor?

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

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

Here is an example:

>>> 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

Why is it not possible to chain a method call with the constructor call?

This was implemented in python3 .

You are assigning obj to the return value of the function print_a (which is None as it has no return). The actual test object was never stored and is therefore no longer in scope when you try to print it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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