【问题标题】:Am I using static method correctly?我是否正确使用静态方法?
【发布时间】:2021-12-31 05:53:00
【问题描述】:

我有一个大类,如下所示:

class Trainer:
    def __init__(self, name, age, height, weight):
        self.name = name
        self.age = age
        self.height = height
        self.weight = weight
    
    def fit(self, dataloader):
        ....DO MODEL TRAINING...
        
        self.save(path=xxx)
        self.load(path=xxx)
    
    def save(self, path):
        self.model.eval()
        torch.save(self.model.state_dict(), path)
    
    @staticmethod
    def load(path: str):
        """Load a model checkpoint from the given path."""
        checkpoint = torch.load(path, map_location=torch.device("cpu"))
        return checkpoint

here,我看到由于我的load()不需要self,因为在load方法中,我们不调用self,那么我们应该使用staticmethod。这是正确的吗?

【问题讨论】:

    标签: python deep-learning


    【解决方案1】:

    是的,您可以在这里使用静态方法。要使用静态方法,我们不需要传递类实例 self 参数来处理。静态方法就像,它们只是独立于类的实例。并且可以直接通过Class_name.static_method_name调用,无需创建实例来访问方法。

    更多阅读here

    【讨论】:

      猜你喜欢
      • 2015-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-26
      • 2019-03-31
      • 2012-06-17
      • 2011-02-12
      • 1970-01-01
      相关资源
      最近更新 更多