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()

class Person:age = 25def printAge(cls):print('The age is:', cls.age)# create printAge class method
Person.printAge = classmethod(Person.printAge)Person.printAge()When you run the program, the output will be:
The age is: 25
The age is: 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

from datetime import date# random Person
class Person:def __init__(self, name, age):self.name = nameself.age = age@classmethoddef 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 classnameand 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 = nameself.age = age@staticmethoddef fromFathersAge(name, fatherAge, fatherPersonAgeDiff):return Person(name, date.today().year - fatherAge + fatherPersonAgeDiff)@classmethoddef 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.

转载于:https://www.cnblogs.com/Xingtxx/p/11045997.html

Python classmethod()相关推荐

  1. python classmethod_Python classmethod()

    The classmethod() method returns a class method for the given function. classmethod()方法返回给定函数的类方法. T ...

  2. Python eval()函数的使用

    Python eval()函数的使用 文章目录 一.官网给出的定义 1.eval() 方法的语法: 二.eval的作用 1.计算字符串中有效的表达式,并返回结果 2.将字符串转成相应的对象(如list ...

  3. Python xrange()函数

    Python xrange() function is used to generate a sequence of integers. This function is part of Python ...

  4. Python ord(),chr()函数

    Python ord() and chr() are built-in functions. They are used to convert a character to an int and vi ...

  5. Python bytearray()

    Python bytearray() function returns a bytearray object that contains the array of bytes from the inp ...

  6. Python complex()

    Python complex() function is used to create complex numbers. It's a built-in function that returns a ...

  7. Python Frozenset()

    Python frozenset is an unordered collection of distinct hashable objects. Frozenset is an immutable ...

  8. Python strftime()

    Python strftime() function is present in datetime and time modules to create a string representation ...

  9. Python raw_input()

    Good day, learners. In our previous tutorial we learned about Python SimpleHTTPServer. In this tutor ...

  10. Python sorted()函数

    Python sorted() function returns a sorted list from the items in the iterable. Python sorted()函数从ite ...

最新文章

  1. python使用matplotlib可视化线图(line plot)、将可视化图像的图例(legend)放置在图像外部、底部区域
  2. 2011,我的IT我的梦
  3. 搜索,然后学习:两阶段的无监督文本生成
  4. C# 系统应用之ListView控件 (二).加载选中节点文件夹下文件信息
  5. 【arc101】比赛记录
  6. 驱动框架3——初步分析led驱动框架源码
  7. Linux系统下授权MySQL账户访问指定数据库和数据库操作
  8. Start Developing iOS Apps Today系列(二)
  9. 前端安全系列之二:如何防止CSRF攻击?
  10. MATLAB R2016a 简单介绍
  11. [分层最短路板子] 洛谷 P4568
  12. 大数据计算技术架构解析
  13. 医院影像服务器系统,锐潮医学影像管理系统(PACS)
  14. 【实习小tip】多层dialog弹窗遮罩问题、elementUI的form表单组件的select框在只读的情况下没办法拿到传来的数据、从弹窗子组件获取数据后需要刷新页面
  15. 漏损分析指标定义(部分)
  16. Redis的一些知识
  17. Android实现图片放大缩小
  18. 单片机外围模块漫谈之三,CAN总线
  19. Python黑帽子--黑客与渗透测试编程之道 python3 实现代码
  20. Android Ubuntu平台下ADB驱动的安装

热门文章

  1. Atitit 信息系统安全法 目录 1. 常见的安全保护目标 1 2. WEB安全风险行为 2 2.1. Injection 2 2.2. Broker Authentication损坏的身份验证
  2. Atitit.软件与编程语言中的锁机制原理attilax总结 1. 用途 (Db,业务数据加锁,并发操作加锁。 2 2. 锁得类型 3 2.1. 排它锁 “互斥锁 共享锁 乐观锁与悲观锁 乐观锁:
  3. Atitit.词法分析的理论原理 part2
  4. 自动化设置chrome禁止显示图片及恢复
  5. Julia : Some, something, Nothing
  6. 监管科技崛起:从FinTech到RegTech
  7. 阿里云:我们为全面服务政企市场做好了准备!
  8. Kafka从上手到实践 - 实践真知:搭建Kafka相关的UI工具 | 凌云时刻
  9. Kafka开源转商业实践,助力车主无忧系统稳健 | 凌云时刻
  10. 毕设题目:Matlab图像去噪