问题描述
如何在静态方法中获得对类的引用?
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping>
<property name="mappings" >
<props>
<prop key="/**/index.htm">controller1</prop>
<prop key="/**/index.cache">controllercache</prop>
</props>
</property>
</bean>
但是我想B.load_from_file返回类型B的对象,而不是A。 我知道load_from_file是否不是我可以做的静态方法
class A:
def __init__(self,*args):
...
@staticmethod
def load_from_file(file):
args = load_args_from_file(file)
return A(*args)
class B(A):
...
b = B.load_from_file("file.txt")
解决方法
这就是classmethod
的用途;它们就像staticmethod
一样,它们不依赖实例信息,但是它们 do 提供有关被调用的 class 的信息,方法是隐式提供作为第一个论点。只需将您的备用构造函数更改为:
@classmethod # class,not static method
def load_from_file(cls,file): # Receives reference to class it was invoked on
args = load_args_from_file(file)
return cls(*args) # Use reference to class to construct the result
调用B.load_from_file
时,cls
将是B
,即使方法是在A
上定义的,也可以确保构造正确的类。
通常,每当您发现自己编写这样的备用构造函数时,总是 希望classmethod
正确启用继承。