简体   繁体   中英

Python3 calls function directly from class name. Utility function? Static function? Or implicit instantiate an object

I am looking the following python3 code:

class MyClass(MyAbstractClass):
      :
    def my_fun1(self, input1):
         :
        return result

Then at other part of the codes, MyClass is used like:

output = MyClass().my_fun1(input1)

I am wondering does MyClass().my_fun1(input1) instantiate an object of MyClass implicitly? Or MyClass() here is treated as a utility function class? If it is a utility function, why bother put it within a class? Or is it a static class? but it the my_fun1 isn't marked as a static function?

Sorry I am coming from C++/Java background, so this is a bit strange to me ...

Thanks a lot!

Calling MyClass().my_fun1(input1) instantiats an object of MyClass first (since MyClass() calls the constructor) and then calls my_fun1 function. In Python, there is no static class, but we do have static method and class method. You could find many good references for these concepts such as HERE and HERE .

If you define a static method in MyClass , you will need to call it in the following manner:

output = MyClass.my_static_method(input1)

Note that there is no () after MyClass , meaning you are not creating an object (instance).

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