问题
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!
回答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
回答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(...)
回答3:
__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.
来源:https://stackoverflow.com/questions/38840580/how-to-return-a-class-instance-in-member-function-of-a-class