python class
分為三個部分:class and object(類與對象),inheritance(繼承),overload(重載)and override(覆寫)。
class and object
類的定義,執行個體化,及成員通路,順便提一下python中類均繼承于一個叫object的類。
class Song(object):#definition
def __init__(self, lyrics):
self.lyrics = lyrics#add attribution
def sing_me_a_song(self):#methods
for line in self.lyrics:
print line
happy_bday = Song(["Happy birthday to you",
"I don't want to get sued",
"So I'll stop right there"])#object1
bulls_on_parade = Song(["They rally around the family",
"With pockets full of shells"])#object2
happy_bday.sing_me_a_song()#call function
bulls_on_parade.sing_me_a_song()
inheritance(繼承)
python支援繼承,與多繼承,但是一般不建議用多繼承,因為不安全哦!
class Parent(object):
def implicit(self):
print "PARENT implicit()"
class Child(Parent):
pass
dad = Parent()
son = Child()
dad.implicit()
son.implicit()
overload(重載)and override(覆寫)
重載(overload)和覆寫(override),在C++,Java,C#等靜态類型語言類型語言中,這兩個概念同時存在。
python雖然是動态類型語言,但也支援重載和覆寫。
但是與C++不同的是,python通過參數預設值來實作函數重載的重要方法。下面将先介紹一個C++中的重載例子,再給出對應的python實作,可以體會一下。
C++函數重載例子:
void f(string str)//輸出字元串str 1次
{
cout<<str<<endl;
}
void f(string str,int times)//輸出字元串 times次
{
for(int i=0;i<times;i++)
{
cout<<str<<endl;
}
}
python實作:
通過參數預設值實作重載
<span style="font-size:18px;">def f(str,times=1):
print str*times
f('sssss')
f('sssss',10)</span>
覆寫
class Parent(object):
def override(self):
print "PARENT override()"
class Child(Parent):
def override(self):
print "CHILD override()"
dad = Parent()
son = Child()
dad.override()
son.override()
super()函數
函數被覆寫後,如何調用父類的函數呢?
class Parent(object):
def altered(self):
print "PARENT altered()"
class Child(Parent):
def altered(self):
print "CHILD, BEFORE PARENT altered()"
super(Child, self).altered()
print "CHILD, AFTER PARENT altered()"
dad = Parent()
son = Child()
dad.altered()
son.altered()
python中,子類自動調用父類_init_()函數嗎?
答案是否定的,子類需要通過super()函數調用父類的_init_()函數
class Child(Parent):
def __init__(self, stuff):
self.stuff = stuff
super(Child, self).__init__()