是否可以导入类方法而不实例化类?
问题描述:
上课位于my_module.py地方是否可以导入类方法而不实例化类?
我可以访问他的方法是这样
from .my_module import Mailer
mailer = Mailer()
mailer.do_stuff()
但如果我可以从类只导入do_stuff
方法?如果是这样,我可以不仅导入静态方法吗?
答
您可以在类上访问类和静态方法,无需创建实例。例如,采取下面的演示类:
class Demo(object):
def instance_method(self):
print "Called an instance method"
@classmethod
def class_method(cls):
print "Called a class method"
@staticmethod
def static_method():
print "Called a static method"
现在,我们可以调用两个直接在类的那些方法:
>>> Demo.class_method()
Called a class method
>>> Demo.static_method()
Called a static method
但是,我们不能称之为实例方法,因为我们没有一个实例为self
参数:
>>> Demo.instance_method()
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
Demo.instance_method()
TypeError: unbound method instance_method() must be called with Demo instance as first argument (got nothing instead)
可以调用所有这三种方法对一个实例:
>>> instance = Demo()
>>> instance.class_method()
Called a class method
>>> instance.static_method()
Called a static method
>>> instance.instance_method()
Called an instance method
需要注意的是静态方法不使用任何类或实例属性,因此它们几乎相同的功能。如果您发现自己想要在不引用类或实例的情况下调用某个函数,只需将其分解为一个函数即可。
如果您有一个静态方法需要与类分开使用,请将其设置为函数*。 *“初始化”*是什么意思?您可以在不创建实例的情况下访问类和静态方法('Mailer.do_stuff()'),但不是无需初始化类对象(因为直到发生这种情况*它们不存在*)。 – jonrsharpe 2015-02-12 09:14:26
是的,你知道了,我的意思是类的实例化 – micgeronimo 2015-02-12 09:44:36