Python类方法适合静态vs实例

2024-03-29 14:43:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试整理如何组织大量代码来迭代存储在python类实例中的数据。在大多数情况下,代码读取实例数据并生成一些结果(数字、列表等)

本质上,我只是试图通过创建顶级实例方法来保持所有内容的可维护性和易读性,这些方法将繁重的工作委托给其他需要实例数据但不需要修改实例本身的“愚蠢”方法

考虑到这些其他方法的只读特性,我最好将它们声明为静态方法并将所需的数据作为单独的参数传递,还是将它们全部作为实例方法传递

我更喜欢静态方法方法,因为“self”参数表示该方法修改实例数据,但我不知道是否过度使用静态方法来采用该方法

我意识到这是一个广泛的问题,需要基于意见的回答,但我找不到任何信息表明过度使用静态方法会造成任何实际困难/性能问题(反之亦然)。也就是说,我看到了一些建议,认为应该谨慎使用静态方法,但我看不到任何理由

例如,在下面的代码片段中,假设静态方法表示对实例数据的重要但独立的操作,那么最好将它们标记为静态方法(这告诉我它们只返回结果,而不修改实例或类),还是使它们都是实例级方法并直接访问数据?这种方法有没有真正的问题

class Test(object):

    def __init__(self):
        self.var1 = 10
        self.var2 = ["my", "list", "of", "strings"]
        self.var3 = [1,2,3,4,5]

    @staticmethod
    def processFloat(inst_float):
        pass

    @staticmethod
    def processList(inst_list):
        pass

    @staticmethod
    def processArray(inst_array):
        pass

    def doStuff(self):
        processFloat(self.var1)
        processList(self.var2)
        processArray(self.var3)

Tags: 数据实例方法代码selfdefpasslist
1条回答
网友
1楼 · 发布于 2024-03-29 14:43:49

我想你一定误解了self参数的用法。它用于引用您正在使用的类的实例。必须使用实例方法来访问实例数据(无论是否修改实例数据),使用静态方法根本无法获取数据*

考虑以下几点:

class Test(object):
    def __init__(self):
        self.my_instance_variable = 7

    def get_variable(self):
        return self.my_instance_variable

    @staticmethod
    def try_and_get_stuff():
        return self.my_instance_variable
        # This is not valid! "self" is undefined!
        # What other variable could we use here instead of self?
        # None! Because we don't have a reference to any instance!

a = Test()
# This is fine:
print(a.get_variable())
# This is fine too:
print(a.my_instance_variable)
# These are not fine:
print(Test.get_variable())
print(Test.my_instance_variable)
# Test has no variable called my_instance_variable until an instance of Test
# is instantiated!

现在,您可能需要编写一些与Test相关的helper方法,静态方法可能是放置它的好地方。但是您需要显式地向它传递Test的实例,以便它处理:

class Test(object):
    def __init__(self, start_value):
        self.my_instance_variable = start_value

    def get_variable(self):
        return self.my_instance_variable

    @staticmethod
    def process_some_instances(list_of_test_instances):
        score = 0
        for my_test in list_of_test_instances:
            score = score + my_test.get_variable()
        return score

a = Test(8)
b = Test(9)
instance_list = [a, b]
print(Test.process_some_instances(instance_list)

也可以在模块级将这些方法声明为函数。我通常喜欢将它们放在类中,如果它们与特定类相关,则作为静态或类方法,但这是个人喜好的问题。如果您来自Java或类似的背景,那么您可能比模块级函数更容易理解静态方法

(*除非你做了一些超出这个问题范围的可怕的事情,你不应该在这里考虑)

相关问题 更多 >