1. 程式人生 > >Python--繼承Object物件

Python--繼承Object物件

關於Python Object繼承的相關總結

在Python中所有的類都繼基類object,基類object擁有__ setattr__()和__ getattribuate__()兩個常用的方法,__ setattr__()用於根據指定的name設定物件中相應屬性的value,而__ getattribuate__()用於通過相應的name獲取物件中相應的屬性的value。 當呼叫 instance.name = value 的形式的時候,預設呼叫instance.__ setattr__(name,value ),而當呼叫以下instance.name形式的時候,預設呼叫instance.__ getattr__(name)方法。

class Book(object):
	'''
	def __init__(self,name,value):
		self.name = name
		self.value = value
	'''
	def __setattr__(self,name,value):
		object.__setattr__(self,name,value)
	def __getattr__(self,name):
		try:
			return object.__getattribute__(name)
		except:
			return name + " is not found!"
	def
__str__(self): return self.name + " Meet "+ str(self.value) def main(): c = Book() # c = Book('Python',"Hello World!") c.name = 'Python' c.value = "Hello World!" c.hello = 'hello' print(c.name) print(c.value) print(c) if __name__ == '__main__': main()

輸出的結果如下所示:

Python
Hello World!
Python Meet Hello World!
[Finished in 0.3s]