python的cls,self,classmethod,staticmethod
来源:互联网 发布:eviews软件中文版下载 编辑:程序博客网 时间:2024/05/20 05:04
python类里会出现这三个单词,self和cls都可以用别的单词代替,类的方法有三种,
一是通过def定义的 普通的一般的,需要至少传递一个参数,一般用self,这样的方法必须通过一个类的实例去访问,类似于c++中通过对象去访问;
二是在def前面加上@classmethod,这种类方法的一个特点就是可以通过类名去调用,但是也必须传递一个参数,一般用cls表示class,表示可以通过类直接调用;
三是在def前面加上@staticmethod,这种类方法是静态的类方法,类似于c++的静态函数,他的一个特点是参数可以为空,同样支持类名和对象两种调用方式;
代码:
class A: member = "this is a test." def __init__(self): pass @classmethod def Print1(cls): print "print 1: ", cls.member def Print2(self): print "print 2: ", self.member @classmethod def Print3(paraTest): print "print 3: ", paraTest.member @staticmethod def print4(): print "hello" a = A() A.Print1() a.Print1() #A.Print2() a.Print2() A.Print3() a.Print3() A.print4()
输出:
print 1: this is a test.print 1: this is a test.print 2: this is a test.print 3: this is a test.print 3: this is a test.hello[Finished in 0.4s]
0 0
- python的cls,self,classmethod,staticmethod
- python的cls,self,classmethod,staticmethod
- python的cls,self,classmethod,staticmethod
- python的cls,self,classmethod,staticmethod
- python的cls,self,classmethod,staticmethod
- python的staticmethod、classmethod
- python 的@classmethod &&@staticmethod
- python的staticmethod和classmethod
- python的@classmethod和@staticmethod
- Python @staticmethod 和 @classmethod 的异同
- 理解python的staticmethod与classmethod实现
- 【Python】Staticmethod和classmethod的区别
- 理解python的staticmethod与classmethod实现
- Python中的staticmethod和classmethod 的异同
- python中staticmethod和classmethod的区别
- Python的classmethod和staticmethod区别
- python中classmethod和staticmethod的区别
- Python @classmethod 和 @staticmethod的比较
- js闭包
- 【题解】Binary Tree Right Side View
- 一网打尽当下NoSQL类型、适用场景及使用公司
- raspberrypi 2 共享电脑网络
- Android 自定义View (0)
- python的cls,self,classmethod,staticmethod
- Java正则表达式总结
- 关于VS2010编译CERTI3.4.3中的error MSB6006问题的处理
- 【Opencv】大律法求阈值+分割图像计算像素比
- 12款很棒的浏览器兼容性测试工具
- c语言009---作用域,生命周期,内存数据存储
- T001_UT001_0013
- HDU 3577 Fast Arrangement
- 徐汉彬:Web系统大规模并发——电商秒杀与抢购