gpt4 book ai didi

Python 类方法和(?)实例方法

转载 作者:太空宇宙 更新时间:2023-11-03 12:57:33 24 4
gpt4 key购买 nike

我编写了一个用于解析特定文本格式的 Python 类。

class Parser(object):

def __init__(self):
# Initialize parser instance


def parseFile(self , filename):
pass

def modifyParser(self , *args , **kwargs):
pass

#Classmethod has same name as instance method - this does not work.
@classmethod
def parseFile(cls , filename)
parser = Parser( )
return parser.parseFile( filename )

如前所述,可以使用 modifyParser 方法修改解析器 - 但在大多数情况下,我将只使用来自 Parser.__init__() 的 Parser 实例.我希望能够做到这一点:

# Parse file using 'custom' parser:
parser = Parser( )
parser.modifyParser( ... )
result = parser.parseFile("file.input")


# Parse using the default parser - do not explicitly instantiate an object:
result = Parser.parseFile("file.input")

这要求 parseFile( ) 方法既可以作为实例方法(使用 self)调用,也可以作为类方法调用。这可能吗?形式不对?

最佳答案

如果我是你,我会提供两个不同的功能:

  1. mymodule.Parser().parseFile()(实例方法),以及
  2. mymodule.parseFile()(使用默认实例的模块级函数)。

例如,标准 json 会发生这种情况模块,其中有 json.JSONDecoder().decode()json.loads()。提供两个截然不同的函数可以使代码更明确、更明确和更可预测(在我看来)。

但是,是的:你想做的是可能的。你必须实现自己的 descriptor使用 __get__。这是一个例子:

from functools import partial

class class_and_instance_method(object):

def __init__(self, func):
self.func = func

def __get__(self, obj, type=None):
first_arg = obj if obj is not None else type
return partial(self.func, first_arg)

class Parser(object):

@class_and_instance_method
def parseFile(self):
if isinstance(self, type):
print('using default parser')
else:
print('using the current instance')

>>> Parser.parseFile()
using default parser

>>> p = Parser()
>>> p.parseFile()
using the current instance

关于Python 类方法和(?)实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34879415/

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