The classmethod() method returns a class method for the given function.

classmethod()方法返回给定函数的类方法。

The syntax of classmethod() method is:

classmethod(function)

classmethod() is considered un-Pythonic so in newer Python versions, you can use the @classmethod decorator for classmethod definition.

classmethod()被认为是非Pythonic,因此在较新的Python版本中,您可以使用@classmethod装饰器进行classmethod定义。

The syntax is:

@classmethod

def func(cls, args...)

classmethod() Parameters:

The classmethod() method takes a single parameter:

classmethod()方法采用单个参数:

function - Function that needs to be converted into a class method

function - 需要转换为类方法的函数

Return value from classmethod()

The classmethod() method returns a class method for the given function.

classmethod()方法返回给定函数的类方法。

What is a class method?

A class method is a method that is bound to a class rather than its object. It doesn't require creation of a class instance, much like staticmethod.

The difference between a static method and a class method is:

Static method knows nothing about the class and just deals with the parameters

Class method works with the class since its parameter is always the class itself.

The class method can be called both by the class and its object.

Class.classmethod()

Or even

Class().classmethod()

But no matter what, the class method is always attached to a class with first argument as the class itself cls.

def classMethod(cls, args...)

Example 1: Create class method using classmethod()

classPerson:

age= 25def printAge(cls):

print('The age is:', cls.age)

# create printAgeclassmethod

Person.printAge=classmethod(Person.printAge)

Person.printAge()

When you run the program, the output will be:

The ageis: 25The ageis: 25

Here, we have a class Person, with a member variable age assigned to 25.

We also have a function printAge which takes a single parameter cls and not self we usually take.

cls accepts the class Person as a parameter rather than Person's object/instance.

Now, we pass the method Person.printAge as an argument to the function classmethod. This converts the method to a class method so that it accepts the first parameter as a class (i.e. Person).

In the final line, we call printAge without creating a Person object like we do for static methods. This prints the class variable age.

When do you use class method?

1. Factory methods

Factory methods are those methods which return a class object (like constructor) for different use cases.

It is similar to function overloading in C++. Since, Python doesn't have anything as such, class methods and static methods are used.

Example 2: Create factory method using class method

fromdatetime import date

# random PersonclassPerson:

def __init__(self, name, age):

self.name=name

self.age=age

@classmethod

def fromBirthYear(cls, name, birthYear):return cls(name, date.today().year -birthYear)

def display(self):

print(self.name+ "'s age is:" +str(self.age))

person= Person('Adam', 19)

person.display()

person1= Person.fromBirthYear('John', 1985)

person1.display()

When you run the program, the output will be:

Adam's age is: 19

John's age is: 34

Here, we have two class instance creator, a constructor and a fromBirthYear method.

Constructor takes normal parameters name and age. While, fromBirthYear takes class, nameand birthYear, calculates the current age by subtracting it with the current year and returns the class instance.

The fromBirthYear method takes Person class (not Person object) as the first parameter clsand returns the constructor by calling cls(name, date.today().year - birthYear), which is equivalent to Person(name, date.today().year - birthYear)

Before the method, we see @classmethod. This is called a decorator for converting fromBirthYear to a class method as classmethod().

2. Correct instance creation in inheritance

Whenever you derive a class from implementing a factory method as a class method, it ensures correct instance creation of the derived class.

You can create a static method for the above example but the object it creates, will always be hardcoded as Base class.

But, when you use a class method, it creates the correct instance of the derived class.

Example 3: How class method works for inheritance?

from datetime import date

# random Person

class Person:

def __init__(self, name, age):

self.name = name

self.age = age

@staticmethod

def fromFathersAge(name, fatherAge, fatherPersonAgeDiff):

return Person(name, date.today().year - fatherAge + fatherPersonAgeDiff)

@classmethod

def fromBirthYear(cls, name, birthYear):

return cls(name, date.today().year - birthYear)

def display(self):

print(self.name + "'s age is: " + str(self.age))

class Man(Person):

sex = 'Male'

man = Man.fromBirthYear('John', 1985)

print(isinstance(man, Man))

man1 = Man.fromFathersAge('John', 1965, 20)

print(isinstance(man1, Man))

When you run the program, the output will be:

True

False

Here, using a static method to create a class instance wants us to hardcode the instance type during creation.

This clearly causes a problem when inheriting Person to Man.

fromFathersAge method doesn't return a Man object but its base class Person's object.

This violates OOP paradigm. Using a class method as fromBirthYear can ensure the OOP-ness of the code since it takes the first parameter as the class itself and calls its factory method.

python classmethod_Python classmethod()相关推荐

  1. Python中的“ @”(@)符号有什么作用?

    我正在看一些使用@符号的Python代码,但我不知道它的作用. 我也不知道要搜索什么,因为搜索Python文档时会出现,或者当包含@符号时Google不会返回相关结果. #1楼 此代码段: def d ...

  2. 如何使用Python numpy.where()方法

    In Python, we can use the numpy.where() function to select elements from a numpy array, based on a c ...

  3. Python字符串title()

    Python String title() Python字符串title() Python String title() function returns a title cased version ...

  4. Python字符串isdecimal()

    Python String isdecimal() function returns True if all the characters in the string are decimal char ...

  5. Python字符串isalnum()

    Python string isalnum() function returns True if it's made of alphanumeric characters only. A charac ...

  6. Python字符串count()

    Python String count() function returns the number of occurrences of a substring in the given string. ...

  7. Python字符串splitlines()

    Python String splitlines() Python字符串splitlines() Python String splitlines() function returns the lis ...

  8. Python字符串join()方法

    Python string join() method creates a string from an iterable. It joins all the iterable elements wi ...

  9. Python字符串index()

    Python String index() function returns the lowest index where the specified substring is found. If t ...

最新文章

  1. python批量重命名指定目录下所有文件的后缀名
  2. nginx rewrite重写与防盗链配置
  3. Apache/Nigix + Tomcat + 负载均衡
  4. c语言偏移一个字节,文件偏移量与C语言中的流定位
  5. greenplum gpfdist应用
  6. bash脚本创建变量_创建一个Bash脚本模板
  7. 一文带你 GNN 从入门到起飞,做一个饭盆最稳 GNN 饭人!
  8. 新书预告<******笔记>快赏
  9. Cgi与php-Cgi以及Fast-Cgi与php-fpm的理解
  10. 在记录异常日志的时候包含源代码文件名和行号等信息
  11. prisma 连接不上Postgres
  12. Python爬虫的多线程使用方法
  13. 我应该拿什么来拯救你,我的游戏?
  14. 一天一个面试题之——反射
  15. 交互设计人员什么阶段介入
  16. C. The Intriguing Obsession(组合数学)
  17. windows 的cmd设置代理方法
  18. Word2013如何在中间某页重新编排页码,增加分节符。
  19. spring boot 设置默认主页
  20. 一周技术学习笔记(第67期)-CPU的设计跟开闭原则有关系吗

热门文章

  1. 剑指offer十八之二叉树的镜像
  2. 五年 Web 开发者 star 的 github 整理说明
  3. Tomcat可以在eclipse里启动,可是不能訪问首页的问题
  4. EDA实验课课程笔记(八 )——PT(Prime Time)简介(附录静态时序分析)
  5. linux 建立vnc,51CTO博客-专业IT技术博客创作平台-技术成就梦想
  6. 如何安装Exchange2010上安装更新汇总(Update Rollup)
  7. java基础知识的一些细节问题
  8. 如何:在 Windows 窗体 ListView 控件中启用平铺视图 【转载】
  9. php 返回josn 中文,php返回json数据中文显示不友好的问题的解决办法
  10. SM4国密标准 GB/T 32907-2016