类名大写开头;
构造函数
class Obj(Object) nouse = "helo" #类变量,实例共享(类似每个实例复制了一份,而不是static成员), 无法在函数中直接访问到,可以用self.nouse访问 dict = {"k":"ve"} # 这个是所有实例共享的, 实例一个修改会影响到其他实例的dict(每个实例支拷贝了指针?) def __init__(self, args): self.name = .... #成员属性 def __del__(self): #类似析构 ...
成员函数:
def mem_fun(self): ... @staticmethod #类似静态函数,无法用实例对象.来调用 def test(self): print("talk") @property def name(self): return self.name
所有的函数都要有self参数, 作用如同this指针; self代表实例本身;
如:
O.mem_fun() ⇒ Obj.mem_fun(O)
@property 代表属性, 虽然是成员函数,但调用的时候只能以成员属性的方式调用,不能像函数一样调用;
O.name # ⇒ name
私有函数
def __sFunc(self): #两个下划线 ...
私有属性
self.__sV = 5 #两个下划线: 私有 # 强制调用私有 print(O._Obj__sV )
继承
class Animal(Object):
def __init__(self, arg1):
...
#子类
class People(Animal): #基类名字作为参数
def __init__(self, arg1, arg2): # 额外参数加入后面
Animal.__init__(self, arg1)
self. v2 = arg2
#默认参数
def __init__(self,arg1,arg2,age=20,country='china'):
self.arg1=arg1
self.arg2=arg2
self.age=age
self.country=country
#使用时:
People(arg1,arg2,'american') #这时'american'是赋给了age的(动态类型的原因), country 是默认的'china'; 可以使用命名参数的形式: country = 'american'
People(arg1,arg2,country = 'american' )
多重继承
加上一个新类:
class Career(object): def __init__(self, Id): pass #继承 class People(Animal, Career): # 直接写这 def __init__(self, arg1): Animal.__init__(self, arg1) Career.__init__(self) # 参数问题怎么解决? def P(self): print("the out is %s, %s " % ())
测试与import分离
if __name__=='__main__':
# test code typing here, will not run when imported as a module
类实例的存储到数据库
把实例存储到数据库中, 即便程序结束了, 以后仍然可以使用;
工具; Pickle, Shelve
Shelve使用;
- 如上面的类保存在people.py文件里;
- 现在在另一个文件中生成几个实例:
#"store.py" from people import People #导入People类 laowang = People("lao", "wang", 20) xiaoming = People("xiao","ming",30) #上面生成了2个实例, 下面将通过shelve保存实例到文件中 import shelve db = shelve.open('pl') for obj in (laowang, xiaoming): db[obj.name] = obj db.close()
运行后就会在文件交下生成三个文件:pl.dir, pl.dat, pl.bak;
使用时,仍然通过shelve来操作, 如下面是命令行操作(People类所在的文件要和到处的实例文件在一起, 或相关路径才能搜索到):
import shelve db = shelve.open('pl') list(db.keys()) # ⇒ ['laowang', 'xiaoming'] lw = db['laowang'] lw.info() # 调用方法
多态
基类中定义的函数可以被子类覆盖; 函数都是类似虚函数的形式,所以子类调用时, 调用的是子类的函数;
class base: def __init__(self): pass def delegete(self): self.action() #action函数可以不在父类定义, 但如果同时没在子类定义则会出现错误 def action(self): assert False, " no defined in derive class" class derive: def __init__(self): pass def action(self): print("action is done in derive")
上面的例子中,如果derive类中没有定义action函数则会调用base中的action, 此时会直接触发崩溃;
抽象类
抽象类和C++中的概念一样,无法生成实例
''' this is the specifying words as the __doc__ attribute of module ''' from abc import ABCMeta, abstractmethod class Super(metaclass=ABCMeta) ''' this is the class specifying words ''' @abstractmethod def method(self): pass # 纯虚函数
用@abstractmethod声明了的函数必须在子类中实现;