類定義
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def print_score(self):
print '%s: %s' % (self.__name, self.__score)
說明:init為構(gòu)造函數(shù),第一個參數(shù)為self為函數(shù)本身。
類成員以雙下劃線開頭,說明為private訪問限制的,類實例不能直接訪問。(一個下劃線開頭的實例變量名,外部是可以訪問的。其實雙下劃線的變量,python將其改名為"類名變量名",類實例可以通過如上標(biāo)識訪問,但是、總之訪問這些變量是不好的。)
類繼承
class Animal(object):
def run(self):
print 'Animal is running...'
class Dog(Animal):
pass
class Cat(Animal):
def run(self): #方法的overwrite
print 'Dog is running...'
dog = Dog()
dog.run()
cat = Cat()
cat.run()
#多態(tài)--父類是參數(shù)
def run_twice(animal):
animal.run()
animal.run()
#如下兩個都可以正常運行
run_twice(Animal())
run_twice(Dog())
類繼續(xù)可以共用父類公共方法,可重寫父類的不適宜方法;
多態(tài)在類作為參數(shù)時,可以接收父類型的參數(shù),把子類視作父類型參數(shù)進(jìn)行調(diào)用。
type() 方法可獲取對象類型
import types
types模塊中有相應(yīng)類型定義
>>> type('abc')==types.StringType
True
>>> type(u'abc')==types.UnicodeType
True
>>> type([])==types.ListType
True
>>> type(str)==types.TypeType
True
有一種類型就叫TypeType,所有類型本身的類型就是TypeType
isinstance() 判斷變量是否為某類實例
dir() 獲得一個對象的所有屬性和方法
len() 返回對象長度(自動去調(diào)用該對象的len()方法)
>>> class MyObject(object):
... def __init__(self):
... self.x = 9
... def power(self):
... return self.x * self.x
...
>>> obj = MyObject()
>>> hasattr(obj, 'x') # 有屬性'x'嗎?
True
>>> hasattr(obj, 'y') # 有屬性'y'嗎?
False
>>> setattr(obj, 'y', 19) # 設(shè)置一個屬性'y'
>>> hasattr(obj, 'y') # 有屬性'y'嗎?
True
>>> getattr(obj, 'y') # 獲取屬性'y'
19
>>> getattr(obj, 'z', 404) # 獲取屬性'z',如果不存在,返回默認(rèn)值404
404
#如上也可以應(yīng)用于方法