1. self, cls 不是关键字
在python里面,self, cls 不是关键字,完全可以使用自己写的任意变量代替实现一样的效果
代码1
代码如下:
class MyTest:
myname = 'peter'
def sayhello(hello):
print "say hello to %s" % hello.myname
if __name__ == "__main__":
MyTest().sayhello()
代码如下:
class MyTest:
myname = 'peter'
def sayhello(self):
print "say hello to %s" % self.myname
if __name__ == "__main__":
MyTest.myname = 'hone'
MyTest.sayhello = lambda self,name: "I want say hello to %s" % name
MyTest.saygoodbye = lambda self,name: "I do not want say goodbye to %s" % name
print MyTest().sayhello(MyTest.myname)
print MyTest().saygoodbye(MyTest.myname)
代码如下:
def enhanced(meth):
def new(self, y):
print "I am enhanced"
return meth(self, y)
return new
class C:
def bar(self, x):
print "some method says:", x
bar = enhanced(bar)
代码如下:
class C:
@classmethod
def foo(cls, y):
print "classmethod", cls, y