Python @classmethod decorator and static method All In One
修饰器/装饰器;静态方法;实例方法
# cls
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
# 实例方法
def calculate_area(self):
return self.width * self.height
# 类方法 (类似 js 的 static method)
@classmethod
def new_square(cls, side_length):
return cls(side_length, side_length)
# 类方法
square = Rectangle.new_square(5)
print("类方法", square.calculate_area())
# 类实例方法
s = Rectangle(3, 3)
print("类实例方法", s.calculate_area())
"""
$ py3 ./classmethod-decorator.py
类方法 25
类实例方法 9
"""
demos
(? 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 ?️,侵权必究⚠️!
- classmethod decorator Python static methodclassmethod decorator python static non-static requires static method decorators python how use enforcing decorator function python staticmethod classmethod作用python 矩阵multiply_python staticmethod classmethod decorators python decorators python brief python method magic python method all one