Python中的类属性和实例属性以及静态方法和类方法
来源:互联网 发布:网络参数wan口设置 编辑:程序博客网 时间:2024/05/21 09:01
2
3
4
5
6
'foo'
>>> c.foo
'foo'
>>> C.foo = 'bar'
>>> C.foo
'bar'
>>> c.foo
'bar'
>>> c.foo = 'instantiation'
>>> c.foo
'instantiation'
>>> C.foo
'bar'
calling static method foo().
>>> C.bar()
calling class method bar().
bar() is part of class: C
class C: def __init__(self): pass def foo(): print("calling static method foo().") foo = staticmethod(foo) def bar(a1,b): print("calling class method bar().") print("bar() is part of class:",a1.__name__) bar = classmethod(bar)C.foo()C.bar()----------------------------------------------------------------------------------------
TypeError: bar() takes exactly 2 arguments (1 given)
在PYTHON中,两种方法的主要区别在于参数。实例方法隐含的参数为类实例self,而类方法隐含的参数为类本身cls。
静态方法无隐含参数,主要为了类实例也可以直接调用静态方法。
所以逻辑上类方法应当只被类调用,实例方法实例调用,静态方法两者都能调用。主要区别在于参数传递上的区别,实例方法悄悄传递的是self引用作为参数,而类方法悄悄传递的是cls引用作为参数。
Python实现了一定的灵活性使得类方法和静态方法,都能够被实例和类二者调用
==========================================================================================================@staticmethod A way to write a method inside a class without reference to the object it is being called on. So no need to pass implicit argument like self or cls. It is written exactly the same how written outside the class, but it is not of no use in python because if you need to encapsulate a method inside a class since this method needs to be the part of that class @staticmethod is comes handy in that case.
@classmethod It is important when you want to write a factory method and by this custom attribute(s) can be attached in a class. This attribute(s) can be overridden in the inherited class.
A comparison between these two methods can be as below
- Python中的类属性和实例属性以及静态方法和类方法
- Python中的类属性和实例属性以及静态方法和类方法
- python 类属性,实例属性,类方法,静态方法
- python中的类属性和实例属性
- python中的类属性和实例属性
- python中的类属性和实例属性
- python中的类属性和实例属性
- Python中的类属性、实例属性与类方法、静态方法
- Python:类属性,实例属性,私有属性与静态方法,类方法,实例方法
- Python:类属性,实例属性,私有属性与静态方法,类方法,实例方法
- Python:类属性,实例属性,私有属性与静态方法,类方法,实例方法
- python中的静态属性,静态方法、类方法解读
- python 类和实例绑定属性和方法的总结
- Python 类属性,实例属性,类方法,实例方法,静态方法
- js属性和方法的可见性:私有属性(方法),实例属性(方法),类属性(方法)
- 浅析PHP类中的静态方法以及静态属性
- python中的实例方法、静态变量,静态方法、类方法、类变量和实例变量
- Python学习:给类的实例绑定属性和方法
- iOS 第三课 podfile文件 makeToast第三方错误提示 正则NSPredicate
- 什么是 metadata (元数据)
- Linux 下 安装Mysql
- Android Studio常用快捷键
- XMLHttpRequest Level 2 使用指南
- Python中的类属性和实例属性以及静态方法和类方法
- 听课练习(四)
- 二叉树的三种遍历
- 实现电话、或电邮、或电话号码的登陆
- 软件行业从业十年的产品经理的得失杂谈
- Box2D C++教程-设置世界(World)7
- 数据结构(严蔚敏、吴伟民)——读书笔记-2、 线性表及其基本运算、顺序存储结构
- C#高级编程七十五天----C#使用指针
- poj3692Kindergarten 二分匹配之最大独立集