问题
:rtype: specifies that this is type of returned object
Therefore, when I create object obj
in following snippet I receive warning from IDE, that cls is not callable
, since IDE expects, that cls
is object
of type SomeAbstractClass
, and I want SomeAbstractClass
itself
IDE is right, since this is default behaviour. But how can I specify, that I am returning class, not instance of class?
Specifying type
instead of SomeAbstractClass
helps a bit, but not a solution, since no further introspection available.
def class_selector(data):
"""
:rtype: SomeAbstractClass
:return: Return some class based on given parameters
"""
return get_from.get(data.name)
cls = class_selector(data)
obj = cls(data.more_data)
Meanwhile i solve this by adding """:type: SomeAbstractClass"""
after object creating, but this does not cancel the warning and it's dirty solution.
Btw, talking about python 2.x
回答1:
if the data is an instance of SomeAbstractClass, you can use the following snippets:
example 1:
def class_selector(data):
"""
return: Return the class of data
"""
return type(data)
example 2:
def class_selector(data):
"""
return: Return the class of data.
"""
return data.__class__
And if you want use data.name to specify a class, you can use this:
def class_selector(data):
"""
return: Return a class specified by data.name
"""
return type(globals()[data.name]) #or use globals()[data.name].__class__
and you should catch the KeyError exception when you use this
来源:https://stackoverflow.com/questions/22593560/python-rtype-docstring-restructured-text-for-class-factories-selectors