- 論壇徽章:
- 0
|
繼續(xù)貼我的學(xué)習(xí)筆記。這里所列的都是從C#的角度來(lái)看的,可能覺(jué)得不是很恰當(dāng),但這樣個(gè)人覺(jué)得方便理解。其中有些內(nèi)容參考過(guò)最下面的文章。
函數(shù)的定義
class
Python中的類沒(méi)有什么public、private、protect
構(gòu)造函數(shù)、析構(gòu)函數(shù)
__init__(self)
__del__(self)
類的靜態(tài)變量
class Student
name="abc"
這東西其實(shí)就是相當(dāng)于C#中的靜態(tài)變量,但這里要注意是,初始化類的靜態(tài)變量是這樣的(DiveIntoPython中的例子)
class counter:
count = 0
def __init__(self):
self.__class__.count += 1
實(shí)例的成員變量
class Student
def __init__(self)
self.name = "abc"
屬性定義(類從object繼承,但好像不是必須的,因?yàn)橄旅娴拇a也可以正常使用)
class Student:
def __init__(self):
self.__name="abc"
def GetName(self):
return self.__name
def SetName(self,value):
self.__name = value
def DelName(self):
del self.__name
Name = property(GetName,SetName,DelName,'Student name')
說(shuō)實(shí)話,當(dāng)我看到這樣的代碼,我就不想使用屬性了。這樣定義起來(lái)也太不方便了,還要從object中繼承。而且現(xiàn)在C#中,可以很簡(jiǎn)單的通過(guò)get、set來(lái)實(shí)現(xiàn)屬性了。目前沒(méi)有找到好的理由使用屬性。
只讀屬性(類必須從object繼承,否則就不是只讀的)
class Parrot(object):
def __init__(self):
self._voltage = 100000
@property
def voltage(self):
"""Get the current voltage."""
return self._voltage
私有變量
class Student:
def __init__(self):
self.__name="abc"
很簡(jiǎn)單就是通過(guò)__ 兩個(gè)下劃線開(kāi)頭,但不是結(jié)尾的。就是私有了
私有方法
class Student:
def __Getage(self):
pass
和私有的變量一樣,你可以嘗試一下直接調(diào)用,編譯器會(huì)有相應(yīng)的提示
強(qiáng)制訪問(wèn)私有方法、變量
"私有"事實(shí)上這只是一種規(guī)則,我們依然可以用特殊的語(yǔ)法來(lái)訪問(wèn)私有成員。
上面的方法,我們就可以通過(guò)_類名來(lái)訪問(wèn)
aobj = Student()
aobj._Student__name
aobj._Student__Getage()
靜態(tài)方法
class Class1:
@staticmethod
def test():
print "In Static method..."
方法重載
python是不支持方法重載,但是你代碼了里可以寫(xiě)。Python會(huì)使用位置在最后的一個(gè)。我覺(jué)得這可能以Python存儲(chǔ)這些信息通過(guò)__dict__ 有關(guān),它就是一個(gè)Dict。key是不能相同的。所以也就沒(méi)辦法出現(xiàn)兩個(gè)GoGo 方法調(diào)用
class Student:
def GoGo(self,name):
print name
def GoGo(self):
print "default"
調(diào)用的時(shí)候你只能使用 obj.GoGo()這個(gè)方法。
一些特殊方法
__init__(self) 構(gòu)造函數(shù)
__del__ (self) 析構(gòu)函數(shù)
__repr__( self) repr()
__str__( self) print語(yǔ)句 或 str()
運(yùn)算符重載
__lt__( self, other)
__le__( self, other)
__eq__( self, other)
__ne__( self, other)
__gt__( self, other)
__ge__( self, other)
這東西太多了。大家還是自己看Python自帶幫助吧。
一些特殊屬性
當(dāng)你定義一個(gè)類和調(diào)用類的實(shí)例時(shí)可以獲得的一些默認(rèn)屬性
class Student:
'''this test class'''
name = 'ss'
def __init__(self):
self.name='bb'
def Run(self):
'''people Run'''
@staticmethod
def RunStatic():
print "In Static method..."
print Student.__dict__ #類的成員信息
print Student.__doc__ #類的說(shuō)明
print Student.__name__ #類的名稱
print Student.__module__ #類所在的模塊
print Student.__bases__ #類的繼承信息
obj = Student()
print dir(obj)
print obj.__dict__ #實(shí)例的成員變量信息(不太理解Python的這個(gè)模型,為什么Run這個(gè)函數(shù)確不再dict中)
print obj.__doc__ #實(shí)例的說(shuō)明
print obj.__module__ #實(shí)例所在的模塊
print obj.__class__ #實(shí)例所在的類名
參考文章:
http://www.xwy2.com/article.asp?id=119 |
|