Python中的类方法/实例方法

时间:2013-10-14 20:29:38

标签: 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()

我的想法是否正确?谢谢。

2 个答案:

答案 0 :(得分:2)

不,你不太对劲。对于某个类方法而不是实例方法,您必须使用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之类的简单变量编写访问器,我们只是直接访问它们。

答案 1 :(得分:0)

真。处理对象实例的函数在其参数中应该有self。否则,它们被认为是类方法。

修改

类方法并不意味着静态方法!它们不是静态方法,除非你在类函数@staticmethod之前添加装饰器def