Sup*_*vah 8 python methods module
所以我有一个通用模块,它包含我正在使用的数据和数据类型的处理函数.我希望能够像from common import common(或更好import common)一样包含它并使用像common.howLongAgo(unixTimeStamp)
在我的公共模块中需要做什么?Common是一个由'common'类组成的模块.
bri*_*ice 32
在python模块中公开方法的方法:
模块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"
Run Code Online (Sandbox Code Playgroud)
现在,进口:
>>> 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'
Run Code Online (Sandbox Code Playgroud)
如果要使类方法更有用,请直接导入该类:
>>> from foo import ModClass
>>> ModClass.class_method()
'I am a class method'
Run Code Online (Sandbox Code Playgroud)
您还import ... as ...可以使其更具可读性:
>>> from foo import ModClass as Foo
>>> Foo.class_method()
'I am a class method'
Run Code Online (Sandbox Code Playgroud)
你应该使用哪些是一些品味问题.我个人的经验法则是:
| 归档时间: |
|
| 查看次数: |
19923 次 |
| 最近记录: |