标签:
#!/usr/bin/python
# Filename: class.py
__metaclass__=type class Person: def set_name(self,name): self.name=name def get_name(self): return self.name def set_age(self,age): self.age=age def get_age(self): return self.age def greet(self): print ("hello,world!,I‘m %s." %self.name)
运行测试结果:
1 Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32 2 Type "copyright", "credits" or "license()" for more information. 3 >>> ================================ RESTART ================================ 4 >>> 5 >>> lewis=Person() 6 >>> lc=Person() 7 >>> zhanglei=Person() 8 >>> zhanglei.set_name(‘ZhangLei‘) 9 >>> lewis.greet 10 <bound method Person.greet of <__main__.Person object at 0x02DD8CB0>> 11 >>> lewis.greet() 12 hello,world!,I‘m Lewis Liu. 13 >>> zhanglei.greet() 14 hello,world!,I‘m ZhangLei. 15 >>>
关于类方法中self的说明:(节选自:简明 Python 教程 -----A Byte of Python)
self
。MyClass
和该类的一个对象MyObject
。当你调用这个对象的方法MyObject.method(arg1, arg2)
的时候,Python自动转化为MyClass.method(MyObject, arg1, arg2)
——这就是self
的原理了。self
参数。标签:
原文地址:http://www.cnblogs.com/liuchuang/p/4389423.html