作者hsnu114444 (littleq0903)
看板Python
标题[分享] Class method
时间Sun Sep 26 02:19:04 2010
这是最近遇到一个人的问题,我突然发现其实书上很少提及
光是decorator就很少有书在讲了,但是我觉得有分享出来的需要
Q: Python如何define一个class method?
在Python里面的话,定一个method的话,第一个引数都要吃一个self当做instance的连结
所以你要是class没有实体化的话,呼叫一个method就会发生TypeError
EX class:
>>> class myClass():
... def instMethod(self):
... return self
... def classMethod():
... print 'call classMethod()'
... def classMethod2(self):
... print self
这时候你就会发现你不订第一个引数self,他会做检查引发TypeError不会让你success,
因为他一定要传一个引数进去,所以如果我们要定一个classmethod怎麽办呢?
要利用"@classmethod"这个decorator
>>> class myClass():
... @classmethod
... def classMethod(cls):
... print cls
再去做呼叫看看
>>> myClass.classMethod()
<class __main__.myClass at 0x466150>
就会发现第一个引数不传instance了,改传class
如果有版友还要补充,请多多指教^_^
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.119.135.70
1F:推 apua:我之前接触decorator发现他的功用真的五花八门,非常值得研究 09/26 08:08
2F:推 ericsk:还有 @staticmethod 不传 class 也不传 instance 09/26 10:46
3F:→ hsnu114444:可是@staticmethod拿得到private var吗? 09/26 12:45
4F:→ hsnu114444:decorator真的蛮重要的,我发现: 09/26 12:46
5F:→ hsnu114444:偏向教学的书都不太讲,偏向实作的书比较会讲 09/26 12:46
6F:推 eromoot:真的要好好研究 ... 09/26 13:52
7F:推 liangjr:Python无private var吧 若说是class var的话 09/28 10:24
8F:→ liangjr:ClassName.classVariable一样可以用 09/28 10:24
9F:推 neowaiter:推推 09/28 12:25
10F:→ hsnu114444:private var有阿?变数名称加两条底线在前面 09/29 13:32
11F:→ apua:回楼上,那确实是private,但是可照楼上liangjr提的方法去读 10/01 20:20
12F:推 liangjr:变数名称加双底线只是naming convention 10/05 05:57
13F:→ liangjr:但并没有机制防止你从别的class存取OtherClass.__private 10/05 05:58
14F:→ liangjr:或other_class_instance.__private 所以不能算是真的 10/05 06:00
15F:→ liangjr:支援private variable或method 10/05 06:00
16F:→ liangjr:err... OtherClass._OtherClass__private 10/05 06:38