gpt4 book ai didi

python - 在 Python 中,如何在不将实例传递给它的情况下使用类方法?

转载 作者:太空狗 更新时间:2023-10-29 20:33:05 25 4
gpt4 key购买 nike

所以我有一个通用模块,其中包含我正在使用的数字和数据类型的处理函数。我希望能够像 from common import common 一样包含它(或者更好的只是 import common)并使用像 common.howLongAgo(unixTimeStamp)

在我的通用模块中执行此操作需要什么?。 Common 是一个由“common”类组成的模块。

最佳答案

在 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"

现在,导入:

>>> 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'

如果你想让类方法更有用,直接导入类:

>>> 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'

您应该使用哪些是个人喜好问题。我个人的经验法则是:

  • 通常作用于诸如集合之类的东西,或者执行一些计算或获取一些资源的简单实用函数应该是模块方法
  • 与类相关但不需要类或实例的函数应该是静态方法
  • 与类相关的函数,需要类进行比较,或者访问类变量的函数应该是类方法。
  • 作用于实例的函数应该是实例方法。

关于python - 在 Python 中,如何在不将实例传递给它的情况下使用类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9934134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com