您的位置:首页 > 编程语言 > Python开发

python面向对象

2018-03-22 11:58 309 查看
实例方法

class AddrBookEntry(object): # 类定义
def __init__(self, nm, ph): # 定义构造器
self.name = nm # 设置 name
self.phone = ph # 设置 phone
print ('Created instance for:', self.name)

def updatePhone(self, newph): # 定义方法
self.phone = newph
print ('Updated phone for:', self.name)

class EmplAddrBookEntry(AddrBookEntry):
def __init__(self, nm, ph, id, em):
AddrBookEntry.__init__(self, nm, ph)
self.empid = id
self.email = em

def updateEmail(self, newem):
self.email = newem
print ('Updated e-mail address for:', self.name)


jane = EmplAddrBookEntry('John Doe', '408-555-1212',42, 'john@spam.doe')
jane.updatePhone('415-555-1212')
print(jane.phone)


类的数据属性:类似于C++static对象

class C(object):
foo = 100

print(C.foo)


类方法

class Kls(object):
no_inst = 0
def __init__(self):
Kls.no_inst = Kls.no_inst + 1
@classmethod#告诉编译器是类方法
def get_no_of_instance(cls_obj):
return cls_obj.no_inst

ik1 = Kls()
ik2 = Kls()
print (ik1.get_no_of_instance())
print (Kls.get_no_of_instance())


静态方法:和外部变量有关

class Kls(object):
def __init__(self, data):
self.data = data
@staticmethod
def checkind():
return (IND == 'ON')
def do_reset(self):
if self.checkind():
print('Reset done for:', self.data)
def set_db(self):
if self.checkind():
self.db = 'New db connection'
print('DB connection made for: ', self.data)

IND = 'ON'
ik1 = Kls(12)
ik1.do_reset()
ik1.set_db()


用super调用父类被覆盖的方法

class P(object):
def foo(self):
print ('Hi, I am P-foo()')

class C(P):
def foo(self):
super(C, self).foo()
print ('Hi, I am C-foo()')

p = P()
c = C()
c.foo()


dict:由一个字典组成,包含一个实例的所有属性。键是属性名,值是属性相应的数据

class:实例c对应的类(仅新式类中)

doc:类C的文档字符串

le

module:类C定义所在的模块

实例属性:区别于C++,python可以在运行时添加属性

class C(object): # define class 定义类
pass

c = C()
print(c.__dict__)

c.foo = 1
print(c.__dict__)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 面向对象