首页 > 代码库 > Beginning Python From Novice to Professional (7) - 类

Beginning Python From Novice to Professional (7) - 类

创建简单类:

#!/usr/bin/env python
__metaclass__ = type

class Person:
	def setName(self,name):
		self.name = name
	def getName(self):
		return self.name
	def greet(self):
		print "Hello,world! I'm %s." % self.name
foo = Person()
bar = Person()
foo.setName('Luke Skywalker')
bar.setName('Anakin Skywalker')
foo.greet()
bar.greet()
Hello,world! I'm Luke Skywalker.
Hello,world! I'm Anakin Skywalker.
在调用foo的setName和greet函数时候,foo自动将自己作为第一个参数传入函数中。

Beginning Python From Novice to Professional (7) - 类