Search code examples
python-2.7functionclassinstancereturn-type

How to return a class instance in member function of a class?


I want to return a class instance in member function of a class, my code is:

class MyClass(object):
    def __init__(self, *args, **kwargs):
        [snippet]

    def func(self, *args, **kwargs):
        [snippet]
        return class_instnace_of_MyClass

if __name__ == '__main__':
    obj = MyClass(...)
    newobj = obj.func(...)  # type(newobj) is MyClass

I think I can call __init__() in func(), and return a new instance of MyClass, but I don't think it is a Pythonic way to do so. How should I do that? Thank you!


Solution

  • I feel like you should use the @classmethod decorator for this, if I'm reading your question right. Something like:

    class myClass(object):
    
        def __int__(name):
            self.name = name
    
        @classmethod
        def from_fancy(cls, name):
            #do something with name, maybe make it 
            #lowercase or something...
            return cls(name)
    

    For example, in the pandas package you can create a DateFrame object by doing things like pandas.DataFrame.from_csv(...) or pandas.DataFrame.from_json(...). Each of those are class methods which return a DataFrame object, created with different initial data sets (csv text file or a JSON text file).

    For instance, you would call it like:

    my_new_object = myClass.from_fancy("hello world")
    

    There's a good thread on @classmethod here