问题描述
我想在类的成员函数中返回一个类实例,我的代码是:
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
我认为我可以在func()
中调用__init__()
,并返回MyClass的新实例,但是我认为这不是Python的方法.我该怎么办?谢谢!
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!
推荐答案
如果我没看错你的话,我觉得你应该使用@classmethod
装饰器.像这样:
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)
例如,在pandas
包中,您可以通过执行pandas.DataFrame.from_csv(...)
或pandas.DataFrame.from_json(...)
之类的操作来创建DateFrame
对象.这些方法都是返回DataFrame
对象的类方法,该对象使用不同的初始数据集(csv文本文件或JSON文本文件)创建.
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")
@classmethod
此处
这篇关于如何在类的成员函数中返回类实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!