0

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!

Snostorp
  • 544
  • 1
  • 8
  • 14
GoingMyWay
  • 16,802
  • 32
  • 96
  • 149

3 Answers3

2

__init__ is the class' constructor in Python. In no cases does it return anything, meaning its value is None. It is futile to pass an argument to func() that is empty. Your assumption is true, that is not the Pythonic way to create another instance of MyClass.

If you want to create a new instance of MyClass just do this:

obj = MyClass(...) # First instance
newobj = MyClass(...) # Add another instance

Read more on class objects and their instantiation here.

Mestica
  • 1,489
  • 4
  • 23
  • 33
2

To return a new instance from a method, instantiate the class in the method, and return that new instance, like so:

class MyClass(object):
    def __init__(self, *args, **kwargs):
        pass

    def func(self, *args, **kwargs):
        ...
        return MyClass(...)

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

Or instead of the merry-go-round, you could just newobj = MyClass(...)

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
1

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

Community
  • 1
  • 1
reptilicus
  • 10,290
  • 6
  • 55
  • 79