物件導向程式設計的乙個主要優點是重用。繼承是實現同樣的機制之一。在繼承中,類(通常稱為超類)由另乙個類(通常稱為子類)繼承。子類為超類新增了一些屬性。
下面是乙個示例python程式,用於說明如何在python中實現繼承。
# a python program to demonstrate inheritance
# base or super class. note object in bracket.
# (generally, object is made ancestor of all classes)
# in python 3.x "class person" is
# equivalent to "class person(object)"
class person(object):
# constructor
def __init__(self, name):
self.name = name
# to get name
def getname(self):
return self.name
# to check if this person is employee
def isemployee(self):
return false
# inherited or sub class (note person in bracket)
class employee(person):
# here we return true
def isemployee(self):
return true
# driver code
emp = person("geek1") # an object of person
print(emp.getname(), emp.isemployee())
emp = employee("geek2") # an object of employee
print(emp.getname(), emp.isemployee())
輸出 :geek1 false
geek2 true
js如何實現繼承
js繼承有5種實現方式 1 繼承第一種方式 物件冒充 function parent username function child username,password var parent new parent zhangsan var child new child lisi 123456 pa...
js如何實現繼承
js繼承有5種實現方式 1 繼承第一種方式 物件冒充 function parent username function child username,password var parent new parent zhangsan var child new child lisi 123456 pa...
怎樣學好python 零基礎如何學好Python?
零基礎如何學好python?其實零基礎學好python很簡單,python高階需要花費寫氣力,都說python簡單易學,那麼零基礎如何學好python?有哪些必須學的知識?學習的策略技巧有哪些?看傳智播客怎麼說 python上手很容易,基本有其他語言程式設計經驗的人可以在1週內學會python最基本...