当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python classmethod()用法及代码示例


classmethod()是Python中的内置函数,它为给定函数返回类方法。

用法: classmethod(function)

参数:该函数接受函数名称作为参数。


返回类型:该函数返回转换后的类方法。

classmethod()方法绑定到类而不是对象。类方法可以同时由类和对象调用。这些方法可以通过类或对象来调用。下面的示例清楚地说明了上面。

范例1:

# Python program to understand classmethod 
  
class Student:
      
    # creating a variable 
    name = "Geeksforgeeks"
      
    # creating a function 
    def print_name(obj):
        print("The name is:", obj.name) 
          
# creating print_name classmethod 
# before creating this line print_name() 
# can be called only with object not with class 
Student.print_name = classmethod(Student.print_name) 
  
# now this method can be call as classmethod 
# print_name() method is called as class method 
Student.print_name()
输出:
The name is: Geeksforgeeks


范例2:

# Python program to understand classmethod 
  
class Subject:
      
    # creating a variable 
    favorite_subject = "Networking"
      
    # creating a function 
    def favorite_subject_name(obj):
        print("My favorite_subject_name is:", 
                           obj.favorite_subject) 
          
# creating favorite_subject_name classmethod 
# before creating this line favorite_subject_name() 
# can be called only with object not with class 
Subject.favorite_subject_name = classmethod(Subject.favorite_subject_name) 
  
# now this method can be call as classmethod 
# favorite_subject_name() method is called as class method 
Subject.favorite_subject_name()
输出:
My favorite_subject_name is: Networking

classmethod()的使用classmethod()函数用于工厂设计模式,在该模式下,我们想使用类名而不是对象来调用许多函数。


@classmethod装饰器:

@classmethod装饰器,是一个内置的函数装饰器,它是一个表达式,在定义函数后会对其求值。评估的结果使您的函数定义变得模糊。类方法将类作为隐式第一个参数接收,就像实例方法接收实例一样。

用法:

class C(object):
    @classmethod
    def fun(cls, arg1, arg2, ...):
       ....

fun: function that needs to be converted into a class method
returns: a class method for function.
  • 类方法是绑定到类而不是类对象的方法。
  • 他们可以访问类的状态,因为它需要一个指向该类而不是对象实例的类参数。
  • 它可以修改适用于该类所有实例的类状态。例如,它可以修改将适用于所有实例的类变量。

在下面的示例中,我们使用staticmethod()classmethod()检查一个人是否成年。

# Python program to demonstrate  
# use of class method and static method. 
from datetime import date 
  
class Person:
    def __init__(self, name, age):
        self.name = name 
        self.age = age 
      
    # a class method to create a  
    # Person object by birth year. 
    @classmethod
    def fromBirthYear(cls, name, year):
        return cls(name, date.today().year - year) 
      
    # a static method to check if a 
    # Person is adult or not. 
    @staticmethod
    def isAdult(age):
        return age > 18
  
person1 = Person('mayank', 21) 
person2 = Person.fromBirthYear('mayank', 1996) 
  
print (person1.age) 
print (person2.age) 
  
# print the result 
print (Person.isAdult(22))
输出:
21
22
True


相关用法


注:本文由纯净天空筛选整理自ankit15697大神的英文原创作品 classmethod() in Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。