Python 静态方法 类方法
来源:互联网 发布:mac 双重认证 编辑:程序博客网 时间:2024/06/05 19:16
静态方法和实例方法的区别主要体现在两个方面:
1. 在外部调用静态方法时,可以使用"类名.方法名"的方式,也可以使用"对象名.方法名"的方式。而实例方法只有后面这种方式。也就是说,调用静态方法可以无需创建对象。
2. 静态方法在访问本类的成员时,只允许访问静态成员(即静态成员变量和静态方法),而不允许访问实例成员变量和实例方法;实例方法则无此限制。
3. 类方法可以被对象调用,也可以被实例调用;传入的都是类对象,主要用于工厂方法,具体的实现就交给子类处理
4. 静态方法参数没有实例参数 self, 也就不能调用实例参数
# coding: utf-8class Fruit(object): version = 1.0 #静态对象 """docstring for Fruit""" def __init__(self): super(Fruit, self).__init__() self.color = 'blue' def is_clean(cls): print cls.color return True @classmethod def foo(cls): #类方法可以被对象调用,也可以被实例调用;传入的都是类对象,主要用于工厂方法,具体的实现就交给子类处理 Fruit.version += 1 print cls.color print 'calling this method foo()' @staticmethod def pish_color(color): #静态方法参数没有实例参数 self, 也就不能调用实例参数 Fruit.color = color def add_foo(self): Fruit.version += 1if __name__ == "__main__": o = Fruit() o.is_clean() # o.pish_color('Green') # o.foo() Fruit.foo() # o.add_foo() # print o.version # o.foo() # print o.version # print Fruit.version
2 0
- Python 静态类、静态方法
- Python 静态方法 类方法
- Python 静态方法 类方法
- Python 类方法 静态方法
- python类方法、实例方法、静态方法
- Python 静态方法 类方法 实例方法
- python实例方法,静态方法,类方法
- python --类方法、对象方法、静态方法
- Python:类方法、静态方法、实例方法
- Python普通方法、静态方法、类方法
- python --类方法、对象方法、静态方法
- Python普通方法、静态方法、类方法
- python实例方法、静态方法、类方法
- python普通方法、类方法、静态方法
- python类方法 实例方法 静态方法
- python实例方法、类方法、静态方法
- python--类方法、对象方法、静态方法
- python--类方法、对象方法、静态方法
- 关于Java集合类迭代变量的修改
- 使用Freescale DZ60控制单个或多个DS18B20
- 1059. Prime Factors (25)
- iBatis delete
- Qt-pro、pri、prf、prl文件学习
- Python 静态方法 类方法
- 开启博客模式
- Asp.net学习总结
- POJ 1979 Red and Black DFS搜索
- 【最短路】 HDOJ 1535 Invitation Cards
- hdoj 2054 A == B ? 【字符串】
- 头文件互相包含与error C2146: 语法错误 : 缺少“;”的问题
- iBatis select for resultMap
- 浅析JVM内存结构和6大区域