您现在的位置是:网站首页> 编程资料编程资料
Python 类方法和静态方法之间的区别_python_
2023-05-26
390人已围观
简介 Python 类方法和静态方法之间的区别_python_
前言
类中不仅可以有 methods,还可以有变量,这些变量称为类属性,例如如下代码中 Book 类的 TYPES 即为类属性。
类中的方法分为3类:
1. 实例方法 instance method
不使用装饰器
类中的所有方法,如果第一个参数是 self,就是 instance method, self 是创建的类实例,实例方法与实例即对象相关。
(self 可以改成别的名称,但使用 self 是convention,self 是类实例, ),
2. 类方法 class method
使用 @classmethod 装饰
类方法的第一个参数总是 cls。如果方法需要类的信息,用 @classmethod 对其进行装饰, 类方法经常被用作 factory,例如如下代码中的 hardcover 和 paperback 两个 class method 方法就是可用于创建对象的 factory。
(cls 可以改成别的名称,但使用 cls 是convention)
3. 静态方法 static method
使用 @staticmethod 装饰
静态方法并不是真正意义上的类方法,它只是一个被放到类里的函数而已。
尽管如此,仍然称之为方法,但它没有关于 class 或 object 的任何信息,所以它实际上是一个独立的函数,只是被放到了类里,静态方法既没有 self 也没有 cls 参数 。(静态方法可以访问类属性,例如 Book.TYPES)
静态方法通常用于组织代码,例如如果认为将某个函数放到某个类里,整体代码会因此更符合逻辑,于是可以将这个函数变成该类的静态方法。所以如果需要在类里放一个函数进去,此函数不会用到任何关于类或实例的信息,那么就可以用 @staticmethod 对其进行装饰。
三种方法中,实例方法和类方法用得最多,静态方法不常用。
class Book: TYPES = ("hardcover", "paperback") # 精装,平装 def __init__(self, name, book_type, weight): self.name = name self.book_type = book_type self.weight = weight def __repr__(self): return f"" def instance_method(self): print(f"Called instance method of {self}") @classmethod def class_method(cls): print(f"called class method of {cls}") @classmethod def hardcover(cls, name, paper_weight): # cls 名称任意,使用 cls 是 convention # 下一行的cls,改成 Book,代码也能跑,但应该写成 cls, 以避免在 inheritance 可能会遇到的问题 return cls(name, cls.TYPES[0], paper_weight + 100) # @classmethod def paperback(cls, name, paper_weight): # 下一行的cls,改成 Book,代码也能跑,但应该写成 cls, 以避免在 inheritance 可能会遇到的问题 return cls(name, cls.TYPES[1], paper_weight) @staticmethod def static_method(): print("Called static method") book = Book("Dive into Python", Book.TYPES[1], 800) # Called instance method of book.instance_method() # 下一行代码和上一行完全等价 # Called instance method of Book.instance_method(book) # called class method of Book.class_method() # Called static method Book.static_method() h_book = Book.hardcover("Harry Potter", 1500) light = Book.paperback("Python 101", 600) # print(h_book) # print(light) 到此这篇关于Python 类方法和静态方法之间的区别的文章就介绍到这了,更多相关Python类方法内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
相关内容
- Django定时任务Django-crontab的使用详解_python_
- python中的生成器、迭代器、装饰器详解_python_
- Python selenium find_element()示例详解_python_
- Python无法用requests获取网页源码的解决方法_python_
- Python实现双因素验证2FA的示例代码_python_
- Linux环境下安装python3_python_
- python中函数的参数详解_python_
- Pytest测试报告工具Allure的高级用法_python_
- Python实现图像压缩和图像处理详解_python_
- Python的三种主要模块介绍_python_
