Python:静态方法与类方法之间的区别 [英] Python : Difference between static methods vs class method

查看:70
本文介绍了Python:静态方法与类方法之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
Python中的@staticmethod和@classmethod有什么区别?

Possible Duplicate:
What is the difference between @staticmethod and @classmethod in Python?

  • 我正在用python学习OOP,并了解了这两种方法
  • 似乎语法上的差异在于,类方法是作为其第一个参数隐式传递其所属类的
    • I am learning OOP in python and came to know about these two methods
    • It seems that the difference in terms of syntax is that class methods are implicitly passed the class they belong to as their first parameter
    • class Circle:
        all_circles = [] # class variable
      
        @staticmethod
        def total_area():
            for c in Circle.all_circles: # hardcode class name
                # do somethig
      
        @classmethod
        def total_area(cls):
            for c in cls.all_circles: # no hardcode class name
                # do something
      

      我认为类方法更灵活,因为我们不对类进行硬编码

      I see class method as more flexible since we don't hardcode the class

      问题:
      -哪一个更好? @staticmethod或@classmethod?
      -这些方法中的每一种都适合使用哪种方案?

      Question:
      - Is it even a question which one is better? @staticmethod or @classmethod?
      - what are the scenarios suitable to use of each one of these methods?

      推荐答案

      classmethod传递了被调用的类'cls'.有关更多详细信息,请参见: @staticmethod和有什么区别和@classmethod在Python中?

      A classmethod gets passed the class 'cls' that it was called upon. For more details see: What is the difference between @staticmethod and @classmethod in Python?

      这篇关于Python:静态方法与类方法之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆