在Python中,如何在不传递实例的情况下使用类方法?
所以我有一个通用模块,它包含我正在使用的数据和数据类型的处理函数。我希望能够包括它像from common import common
(或更好,但只是import common
)和使用功能,如common.howLongAgo(unixTimeStamp)
在Python中,如何在不传递实例的情况下使用类方法?
这是在我的公共模块需要什么? Common是一个由'common'类组成的模块。
模块foo.py
:
def module_method():
return "I am a module method"
class ModClass:
@staticmethod
def static_method():
# the static method gets passed nothing
return "I am a static method"
@classmethod
def class_method(cls):
# the class method gets passed the class (in this case ModCLass)
return "I am a class method"
def instance_method(self):
# An instance method gets passed the instance of ModClass
return "I am an instance method"
现在,进口:如果你想使类方法更加有用
>>> import foo
>>> foo.module_method()
'I am a module method'
>>> foo.ModClass.static_method()
'I am a static method'
>>> foo.ModClass.class_method()
'I am a class method'
>>> instance = ModClass()
>>> instance.instance_method()
'I am an instance method'
,导入一个Python模块中暴露方法
方式直接上课:
>>> from foo import ModClass
>>> ModClass.class_method()
'I am a class method'
您也可以import ... as ...
以使其更易于阅读:
>>> from foo import ModClass as Foo
>>> Foo.class_method()
'I am a class method'
哪一些你应该使用多少有些口味的问题。我个人的经验法则是:
- 简单实用的功能通常作用于之类的东西收藏,或执行一些计算或获取一些资源应该是模块的方法
- 相关的一类功能,但不需要任何一个类或一个实例应该是静态方法
- 与某个类相关的函数,需要该类进行比较,或者访问类变量应该是类方法。
- 将作用于实例的函数应该是实例方法。
在这样的模块范围内暴露方法是否是通用代码实践?无论如何 - 它的工作非常感谢。 – Supernovah 2012-03-29 22:02:40
用'@ classmethod'装饰你的班级方法是非常清洁的 – Daenyth 2012-03-29 22:06:01
这很普遍。标准库有几个例子。 'os'模块是一个。 – brice 2012-03-29 22:06:59
,如果您有模块common.py和功能是在课堂上共同
class common(object):
def howLongAgo(self,timestamp):
some_code
,那么你应该改变你的方法是静态的方法丝毫装饰@staticmethod
class common(object):
@staticmethod
def howLongAgo(timestamp): # self goes out
some_code
这样你不需要改变整个班级,你仍然可以在课堂上使用self.howLongAgo
class Test(object):
@classmethod
def class_method(cls):
return "class method"
test = Test()
print test.class_method()
[[email protected] scar]$ python ~/test.py
class method
以上是使用现代Python对象进行classmethods的标准方式,而不是旧式类。
或者,您也可能意味着一个静态方法:
class Test(object):
@staticmethod
def static_method():
return "static method"
test = Test()
print test.static_method()
[[email protected] scar]$ python ~/test.py
static method
使用哪种更有意义,你的问题。静态方法通常应该被分离成它们自己的独立功能,在那里使用类是多余的。
是的,但问题是,做'test = Test()'你正在创建一个实例。这是我想要避免的。 – Supernovah 2012-03-29 22:15:17
为什么这些功能在一个类首先?如果他们不需要'self',为什么不把它们移动到模块范围? – 2012-03-29 21:56:23
为了让它们脱离我的主Python文件 – Supernovah 2012-03-29 21:56:53
为了达到这个目的,你不需要把它们放在一个类中。只需将它们移动到一个模块并将它们留在模块级别即可。 – 2012-03-29 22:00:08