Python 基礎(chǔ)
使用環(huán)境:
**mac **
pycharm
python2.7
可以看到的內(nèi)容如下:
函數(shù) 類 私有性 超類 多重繼承
函數(shù)
repr 函數(shù)返回本質(zhì)的字符串或者其他對象
print repr('123')
# 輸出為: '123'
print repr([1,2,3])
#輸出為 [1,2,3]
lambda函數(shù) 匿名函數(shù)
def sq(x):
return x * x
lambda x: x * x
#上面兩個函數(shù)意義相同
callable(getattr(tc, 'funcname')) 查看某個類是否含有某個方法
注意在python3中該方法已不再可用,可以使用hasattr(x,'call')方法
callable(getattr(talk,'mouth'))
# 會輸出True False
super()
super(class,self).init() 類似于OC中的[super init]方法
可以保持超類的屬性和值 或方法
__metaClass__ = type
class Bird:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry :
print "Aaaah..."
self.hungry = False
else:
print "NO, Thanks"
class SongBird(Bird):
def __init__(self):
super(SongBird, self).__init__()
self.sound = 'Squawk'
def sing(self):
print self.sound
set的union()
a = set([1, 2, 3])
b = set([2,3,4])
a.union(b) 或者 a|b 結(jié)果都為set([1, 2, 3, 4])
類
創(chuàng)建類:
# _*_coding:utf8_*_
# 上一句聲明編碼類型
__metaClass__ = type # 確定使用新式類
# 創(chuàng)建一個Person 類
class Person:
def setName(self,name):
self.name = name
def getName(self):
return self.name
def greet(self):
print "Hello World! I'm is %s" % self.name
# 調(diào)用
foo = Person()
bar = Person()
foo.setName('liLei')
bar.setName('hanMeiMei')
print foo.getName()
print bar.getName()
foo.greet()
bar.greet()
如果知道foo 是Person的實例的話 還可以Person.getName(foo) 這樣調(diào)用
私有性
為了將方法或者特征變?yōu)樗接?,只要在它名字的前面加上雙下劃線即可
**代碼示例: **
# _*_coding:utf8 _*_
__metaClass__ = type
class privateClass:
def __privateFunc(self);
print "I'm a private function"
def printPrivateFunc(self):
print "private function is :"
self.__privateFunc()
前面有下劃線的名字不會被帶星號的import語句**from privateClass import * ** 導(dǎo)入
超類
class SPAMFilter(Filter): Filter為SPAMFilter的超類
過濾的例子:
# _*_ coding:utf8 _*_
__metaClass__ = type
class Filter:
def init(self):
self.blocked = []
def filter(self, sequence):
return [x for x in sequence if x not in self.blocked]
class SPAMFilter(Filter):
def init(self): # 重寫超類的init方法
self.blocked = ['SPAM']
s = SPAMFilter()
s.init()
print s.filter(['SPAM', 'SPAM', 'SPAM', 'SPAM', 'back', 'bacon'])
# 輸出為 ['back', 'bacon']
**[x for x in sequence if x not in self.blocked] **等價于
lst = []
for x in sequence:
if x not in self.blocked:
lst.append(x)
如果想要查看一個類是否是另外一個類的子類,可以使用issubclass內(nèi)建函數(shù)
print issubclass(SPAMFilter,Filter)
#輸出為True
print issubclasss(Filter,SPAMFilter)
#輸出為False
如果想要知道已知類的基類(超類)們,可以使用它的特殊特性 bases
print SPAMFilter.__bases__
可以使用**isinstance **方法檢查一個對象是否是一個類的實例
s = SPAMFilter()
print isinstance(s, SPAMFilter)
#輸出 True
print isinstance(s,Filter)
#輸出True
print isinstance(s,str)
#輸出False
多重繼承
python中的類可以繼承多個基類
例如:
class Calculator:
def calculate(self, expression):
self.value = eval(expression)
class Talker:
def talk(self):
print "Hi, my value is ", self.value
# 繼承于Calculator 和 Talker
class TalkCaculator(Calculator, Talker):
pass
tc = TalkCaculator()
tc.calculate('1+2*3')
print tc.talk()
當(dāng)使用多重繼承的時候 有個注意點
當(dāng)繼承的超類都含有相同名字的不同方法,那么必須要注意一下超類的順序,先繼承的超類會重寫后繼承的類中的方法。如果Calculator 和 Talker都有talk方法 則Calculator會重寫Talker的talk方法 使其不能訪問,如果把他們的順序倒過來就會讓Talker的talk方法可以訪問了。
靜態(tài)方法和類成員方法
使用@操作符,在方法(或者函數(shù))的上方將裝飾器列出、從而指定一個或者更多的裝飾器(**多個裝飾器在應(yīng)用時的順序與指定順序相反 **)
例子:
__metaClass__ = type
class MyClass:
@staticmethod
def smeth():
print 'This is a static method'
@classmethod
def cmeth(cls):
print 'This is a class method ', cls
# 調(diào)用
MyClass.smeth()
MyClass.cmeth()
# 輸出
'''
This is a static method
This is a class method of __main__.MyClass
'''
屬性
property 函數(shù)的使用
# _*_ coding:urf8 _*_
__metaClass__ = type
class Rectangle:
self.width = 0
self.height = 0
def setSize(self,size):
self.width, self.height = size
def getSize(self):
return self.width, self.height
size = self.width, self.height
r = Rectangle()
r.width = 10
r.height = 5
print r.size
#輸出為 (10,5)
getattr 、setattr、和它的朋友們
攔截對象的所有屬性訪問是可能的,這樣可以使用舊式類實現(xiàn)屬性。為了訪問屬性的時候可以執(zhí)行代碼,必須使用一些魔法(特殊)方法。下面4中方法提供了需要的功能(在舊式類中只需要后三個)
- getattribute(self, name) :當(dāng)屬性name被訪問時自動被調(diào)用
- getattr(self,name): 當(dāng)特征name被訪問且對象沒有相應(yīng)的特征時被自動調(diào)用。
- setattr(self,name,value) :當(dāng)視圖給屬性name賦值時會被自動調(diào)用
- delattr(self,name):當(dāng)視圖刪除屬性name時會被自動調(diào)用
** 示例**
# _*_coding:utf8_*_
__metaClass__ = type
class Rectangle:
def __init__(self):
self.width = 0
self.height = 0
def __setattr__(self, key, value):
if key == 'size':
self.width, self.height = value
else:
self.__dic__[key] = value
def __getattr__(self, item):
if item == 'size':
return self.width, self.height
else:
raise AttributeError
self.dic 該方法包含一個字典。字典里面是實例的所有屬性 。