How to create a class instance directly with a call to a class method?

Question:

I’m facing a problem that I can’t solve. Is it possible to make pipe be an instance of the class MyClass concerning the call to the class method do_something? And make print(isinstance(pipe, MyClass)) return True. This means that on the call pipe goes through the class method do_something and then reads the constructor __init__.

class MyClass:
    def __init__(self):
        self.my_attr = 42
        print("Attribute initialized to", self.my_attr)
        
    @classmethod
    def do_something(cls):
        print("Doing something...")


pipe = MyClass.do_something()
print(isinstance(pipe, MyClass)) # True
Asked By: Tim

||

Answers:

To create an instance of MyClass and call the do_something method on it you can modify the code like this

class MyClass:
    def __init__(self):
        self.my_attr = 42
        print("Attribute initialized to", self.my_attr)
        
    @classmethod
    def do_something(cls):
        obj = cls()
        print("Doing something...")
        return obj

pipe = MyClass.do_something()
print(isinstance(pipe, MyClass)) # True
Answered By: Ake

You could do this with the walrus operator:

(pipe:=MyClass()).do_something()
print(isinstance(pipe, MyClass))
Answered By: shan

Yes, you can create a class instance directly with a call to a class method by returning an instance of the class within the class method. In this case, you can modify the do_something method to create an instance of MyClass and return it. The code for it is as follows:

class MyClass:
    def __init__(self):
        self.my_attr = 42
        print("Attribute initialized to", self.my_attr)
        
    @classmethod
    def do_something(cls):
        print("Doing something...")
        return cls()  # Create an instance of MyClass and return it


pipe = MyClass.do_something()
print(isinstance(pipe, MyClass))  # True

Now, when you call MyClass.do_something(), it will create an instance of MyClass and return it. As a result, pipe becomes an instance of MyClass, and isinstance(pipe, MyClass) returns True.

Output:

Doing something...
Attribute initialized to 42
True
Answered By: Bilesh Ganguly
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.