Python 简明教程

Python - Class Methods

Methods 从属某个类的对象,用来执行特定的操作。我们可以将 Python 方法分为三种不同的类别:类方法、实例方法和静态方法。

Methods belongs to an object of a class and used to perform specific operations. We can divide Python methods in three different categories, which are class method, instance method and static method.

Python class method 是绑定到该类的一种方法,而不是它的实例。它可以在类本身上调用,而不是该类的实例。

A Python class method is a method that is bound to the class and not to the instance of the class. It can be called on the class itself, rather than on an instance of the class.

许多人常常混淆类方法和静态方法。需要记住的是,虽然这两种方法都是在类上调用的,但是 static methods 无法访问"cls"参数,因此它无法修改类的状态。

Most of us often get class methods confused with static methods. Always remember, while both are called on the class, static methods do not have access to the "cls" parameter and therefore it cannot modify the class state.

不同于类方法, instance method 类的 variables 可以访问对象的实例。此外,它还可以访问类变量,因为其在所有对象中都是通用的。

Unlike class method, the instance method can access the instance variables of the an object. It can also access the class variable as it is common to all the objects.

Creating Class Methods in Python

在 Python 中创建类方法有两种方式:

There are two ways to create class methods in Python −

  1. Using classmethod() Function

  2. Using @classmethod Decorator

Using classmethod() Function

Python 内置函数 classmethod() 将实例方法转换为 class method ,该方法仅使用类引用来调用,而不用对象。

Python has a built-in function classmethod() which transforms an instance method to a class method which can be called with the reference to the class only and not the object.

Syntax

classmethod(instance_method)

Example

在 Employee 类中,使用“ self ”参数(对调用对象的引用)定义 showcount() 实例方法。它打印 empCount 的值。接下来,将方法转换为类方法 counter(),该方法可以通过类引用进行访问。

In the Employee class, define a showcount() instance method with the "self" argument (reference to calling object). It prints the value of empCount. Next, transform the method to class method counter() that can be accessed through the class reference.

class Employee:
   empCount = 0
   def __init__(self, name, age):
      self.__name = name
      self.__age = age
      Employee.empCount += 1
   def showcount(self):
      print (self.empCount)

   counter = classmethod(showcount)

e1 = Employee("Bhavana", 24)
e2 = Employee("Rajesh", 26)
e3 = Employee("John", 27)

e1.showcount()
Employee.counter()

Output

使用对象调用 showcount(),使用类调用 count(),两者都显示了员工计数的值。

Call showcount() with object and call count() with class, both show the value of employee count.

3
3

Using @classmethod Decorator

使用 @classmethod() 装饰器时,需要定义一个类方法,因为它比先声明一个实例方法,然后再将其转换为类方法更便捷。

Use of @classmethod() decorator is the prescribed way to define a class method as it is more convenient than first declaring an instance method and then transforming it into a class method.

Syntax

@classmethod
def method_name():
   # your code

Example

类方法作为备用构造器。使用构造新对象所需的参数定义一个 newemployee() 类方法。它返回构造的对象,类似于 init() 方法所做的。

The class method acts as an alternate constructor. Define a newemployee() class method with arguments required to construct a new object. It returns the constructed object, something that the init() method does.

class Employee:
    empCount = 0
    def __init__(self, name, age):
        self.name = name
        self.age = age
        Employee.empCount += 1

    @classmethod
    def showcount(cls):
        print (cls.empCount)

    @classmethod
    def newemployee(cls, name, age):
        return cls(name, age)

e1 = Employee("Bhavana", 24)
e2 = Employee("Rajesh", 26)
e3 = Employee("John", 27)
e4 = Employee.newemployee("Anil", 21)

Employee.showcount()

现在有四个 Employee 对象。如果我们运行上述程序,则它将显示 Employee 对象的数量:

There are four Employee objects now. If we run the above program, it will show the count of Employee object −

4

Access Class Attributes in Class Method

类属性是属于类的那些变量,其值是该类所有实例共享的。

Class attributes are those variables that belong to a class and whose value is shared among all the instances of that class.

若要在类方法中访问类属性,使用 cls 参数,后接点号 (.) 和属性名称。

To access class attributes within a class method, use the cls parameter followed by dot (.) notation and name of the attribute.

Example

在该示例中,我们在类中访问一个类属性。

In this example, we are accessing a class attribute in class method.

class Cloth:
   # Class attribute
   price = 4000

   @classmethod
   def showPrice(cls):
      return cls.price

# Accessing class attribute
print(Cloth.showPrice())

在运行以上代码时,它将显示以下输出:

On running the above code, it will show the following output −

4000

Dynamically Add Class Method to a Class

Python 的 setattr() 函数用于设置动态属性。如果要向类中添加一个类方法,将该方法名称作为参数值传递给 setattr() 函数。

The Python setattr() function is used to set an attribute dynamically. If you want to add a class method to a class, pass the method name as a parameter value to setattr() function.

Example

以下示例显示如何动态向 Python 类添加类方法。

The following example shows how to add a class method dynamically to a Python class.

class Cloth:
   pass

# class method
@classmethod
def brandName(cls):
   print("Name of the brand is Raymond")

# adding dynamically
setattr(Cloth, "brand_name", brandName)
newObj = Cloth()
newObj.brand_name()

执行以上代码时,将显示以下输出 −

When we execute the above code, it will show the following output −

Name of the brand is Raymond

Dynamically Delete Class Methods

Python del 运算符用于动态删除类方法。如果您尝试访问被删除的方法,代码将引发 AttributeError。

The Python del operator is used to delete a class method dynamically. If you try to access the deleted method, the code will raise AttributeError.

Example

在以下示例中,我们使用 del 运算符删除名为“brandName”的类方法。

In the below example, we are deleting the class method named "brandName" using del operator.

class Cloth:
   # class method
   @classmethod
   def brandName(cls):
      print("Name of the brand is Raymond")

# deleting dynamically
del Cloth.brandName
print("Method deleted")

执行以上代码时,将显示以下输出 −

On executing the above code, it will show the following output −

Method deleted