[英]Class methods/instance methods in Python
我来自Ruby,我已经习惯了Python遵循的“明确过度隐含”的哲学,但我之前对如何实际制作类方法感到困惑。 现在,我希望验证我确实在以下方面是正确的:
类中的每个方法本质上都是Python中的类方法。
例如:
class Employee(object):
employeeCount = 0
def __init__(self, name):
self.name = name
employeeCount += 1
def get_name(self):
return self.name
def get_employee_count():
return employeeCount
如果我理解这是正确的,例如david = Employee("david")
则以下两个是等效的:
david.get_name()
和Employee.get_name(david)
。 同样,我们可以说get_employee_count
也是一个类方法,但它不依赖于任何实例,因此我们不会传入实例。 这就是输入david.get_employee_count()
没有意义的原因,因为这将是Employee.get_employee_count(david)
,但get_employee_count
不接受参数,即实例。 结论是我们只需键入Employee.get_employee_count()
。
我的想法是否正确? 谢谢。
不,你不太对劲。 对于某些类方法而不是实例方法,您必须使用classmethod
装饰器。 并且该方法仍然采用参数,但该参数是类,而不是实例。 所以:
@classmethod
def get_employee_count(cls):
return cls.employeeCount
类实际上并没有在Python中定义它们内部的块作用域,因此在方法中引用employeeCount
是行不通的 - 这就是使用cls
param的原因。
为了澄清,装饰器只是一个函数的包装器 - 它也可以编写
def _get_employee_count(cls):
return cls.employeeCount
get_employee_count = classmethod(_get_employee_count)
和classmethod
是一个内置函数。
另请注意,在Python中(我也认为在Ruby中)我们通常不会为name
类的简单变量编写访问器,我们只是直接访问它们。
真正。 处理对象实例的函数应该在其参数中具有self
。 否则,它们被认为是类方法。
编辑
类方法并不意味着静态方法 ! 他们不是静态方法,除非你加装饰@staticmethod
的前def
类功能从头
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.