Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:静态方法与类方法的区别_Python_Oop - Fatal编程技术网

Python:静态方法与类方法的区别

Python:静态方法与类方法的区别,python,oop,Python,Oop,可能重复: 我正在学习python中的OOP,并开始了解这两种方法 似乎语法方面的区别在于类方法隐式地传递它们所属的类作为它们的第一个参数 我认为类方法更灵活,因为我们不硬编码类 问题: -这甚至是一个问题,哪一个更好@staticmethod还是@classmethod? -这些方法中的每一种都适合使用哪些场景?一个classmethod被传递给调用它的类“cls”。有关更多详细信息,请参阅:dup我想问的问题不是哪一个更好,而是哪一个适合您所处的特定情况。 class Circle:

可能重复:

  • 我正在学习python中的OOP,并开始了解这两种方法
  • 似乎语法方面的区别在于类方法隐式地传递它们所属的类作为它们的第一个参数
我认为类方法更灵活,因为我们不硬编码类

问题:
-这甚至是一个问题,哪一个更好@staticmethod还是@classmethod?

-这些方法中的每一种都适合使用哪些场景?

一个classmethod被传递给调用它的类“cls”。有关更多详细信息,请参阅:

dup我想问的问题不是哪一个更好,而是哪一个适合您所处的特定情况。
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