Python的Self到底是虾米东东?

   

    先贴一段自己测试的代码,是用Python的dictionary实现的一个Hashmap。(Hash的实现方式以后再研究)

   

class HashC():
	def new(self, num_buckets=256):
		"""Initializes a Map with the given number of buckets."""
		aMap = []
		for i in range(0, num_buckets):
			aMap.append([])
		return aMap

	def hash_key(self, aMap, key):
		"""Given a key this will create a number and then convert it to
		an index for the aMap's buckets."""
		print hash(key)
		print len(aMap)
		print hash(key) % len(aMap)
		return hash(key) % len(aMap)

	def get_bucket(aMap, key):
		"""Given a key, find the bucket where it would go."""
		bucket_id = hash_key(aMap, key)
		return aMap[bucket_id]

	def get_slot(aMap, key, default=None):
		"""
		Returns the index, key, and value of a slot found in a bucket.
		Returns -1, key, and default (None if not set) when not found.
		"""
		bucket = get_bucket(aMap, key)

		for i, kv in enumerate(bucket):
			k, v = kv
			if key == k:
				return i, k, v

		return -1, key, default

	def get(aMap, key, default=None):
		"""Gets the value in a bucket for the given key, or the default."""
		i, k, v = get_slot(aMap, key, default=default)
		return v

	def set(aMap, key, value):
		"""Sets the key to the value, replacing any existing value."""
		bucket = get_bucket(aMap, key)
		i, k, v = get_slot(aMap, key)

		if i >= 0:
			# the key exists, replace it
			bucket[i] = (key, value)
		else:
			# the key does not, append to create it
			bucket.append((key, value))

	def delete(aMap, key):
		"""Deletes the given key from the Map."""
		bucket = get_bucket(aMap, key)

		for i in xrange(len(bucket)):
			k, v = bucket[i]
			if key == k:
				del bucket[i]
				break

	def list(aMap):
		"""Prints out what's in the Map."""
		for bucket in aMap:
			if bucket:
				for k, v in bucket:
					print k, v

test = HashC()
mymap = test.new()
test.hash_key(mymap, "a")			

   

 

Python要self的理由

Python的类的方法和普通的函数有一个很明显的区别,在类的方法必须有个额外的第一个参数 (self ),但在调用这个方法的时候不必为这个参数赋值显胜于隐 的引发)。Python的类的方法的这个特别的参数指代的是对象本身,而按照Python的惯例,它用self来表示。(当然我们也可以用其他任何名称来代替,只是规范和标准在那建议我们一致使用self)

 

例子说明:创建了一个类HachC,实例化HachC得到了test这个对象,然后调用这个对象的方法test.new(), test.hash_key(mymap, "a") ,这个过程中,Python会自动转为HachC.hash_key(test,arg1,arg2)

这就是Python的self的原理了。即使你的类的方法不需要任何参数,但还是得给这个方法定义一个self参数,虽然我们在实例化调用的时候不用理会这个参数不用给它赋值。

self在Python里不是关键字。self代表当前对象的地址。self能避免非限定调用造成的全局变量。

 

代码出处: http://learnpythonthehardway.org/book/ex39.html

解释引用: http://sjolzy.cn/Why-should-self-Python.html

 

你可能感兴趣的:(python)