现在的位置: 首页 > 综合 > 正文

Python对象

2016年12月10日 ⁄ 综合 ⁄ 共 633字 ⁄ 字号 评论关闭

对象(类的实例):对象包括特性和方法。特性只是作为对象的一部分的变量,方法则是存储在对象内的函数。方法和其他函数的区别在于方法总是将对象作为自己的第一个参数,这个参数一般称为self。

类:类代表对象的集合,每个对象都有一个类

1.创建自己的类

__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()

>>>foo.setName('ABC')

>>>foo.greet

Hello,world! I'm ABC

在调用foo的setName和greet函数时,foo自动将自己作为第一个参数传入函数中


2.特性、函数和方法

特性是可以在外部访问的

>>>foo.name

'ABC'

让方法或者特性变为私有(从外部无法访问),只要在它的名字前面加上双下划线即可


class Secretive:

	def __inaccessible(self):
		print "Bet you can't see me.."
	def accessible(self):
		print "The secret message is:"
		self.__inaccessible()

现在__inaccessible从外界是无法访问的,而在类的内部还能使用


抱歉!评论已关闭.