我对编程相当陌生,并且一直在学习这个在线 Python 课程。我开始阅读有关类方法、静态方法和实例方法的内容。根据我的理解,静态方法是那些接受对象作为参数并且不修改对象等的方法。
问题1:如果在声明上方使用“@staticmethod”声明,是否会使代码更高效?必须这样做有什么意义呢?我看不出它会在代码中产生什么区别。本质上,未声明的静态方法会对代码产生什么影响。
问题2:类方法到底是什么?我知道它需要的特殊参数是“cls”。但是什么时候应该将方法声明为“@classmethod”呢?为什么?如果不显式地将方法声明为类方法,代码会发生什么变化。
抱歉这个简单的问题!我对编程很陌生,无法真正找到我能理解的答案。如果我的思考方式有缺陷,请告诉我!
我在下面发布了一个包含两者的示例。
from typing import ClassVar
from dataclasses import dataclass, field
@dataclass
class Rectangle:
""" example of class and static methods/functions """
# class ("static") intended constants
ORIGINAL_DEFAULT_DIMENSION:ClassVar[int] = 1.
# class attribute that will change over time
default_dimension:ClassVar[int] = ORIGINAL_DEFAULT_DIMENSION
#instance variables
height: float = field(default = 0.0)
width: float = field(default = 0.0)
#getter
def get_area(self) -> float:
return self.height * self.width
#setter
def set_width_height(self, width:float, hi:float) -> bool:
self.width = width
self.height = hi
return True
@classmethod
def set_default_dim(cls, new_dimension) -> bool:
cls.default_dimension = new_dimension
return True
@staticmethod
def which_is_bigger( rect_1, rect_2 ) -> object:
""" takes two Rectangle objects and
returns a Rectangle reference to the one with
the larger area. """
if rect_1.get_area() > rect_2.get_area():
return rect_1
else:
return rect_2
静态方法就像类之外的任何其他函数一样。您可能遇到它的唯一原因是为了更好的组织。代码有时看起来更好,在类中整齐地聚集在一起。
对于类方法,它们通常用于在对象初始化之前执行一些代码。以这段代码为例:
fp = 'hello.txt'
fp2 = 'world.docx'
class FileManipulator:
def __init__(self, data):
# Let's say, in this example, the data is a list of strings.
...
@classmethod
def from_txt(cls, fp):
# This could return an object with data loaded as the text from a txt file.
return cls(data=processed_data)
@classmethod
def from_docx(cls, fp):
# same thing here
return cls(data=processed_data)