Python开发【第七篇】:面向对象二
字段
- class Foo:
- #静态字段(保存在类中)
- CC = 123
- def __init__(self):
- #普通字段(保存在对象中)
- self.name = 'alex'
- def show(self):
- print(self.name)
静态字段的应用:
- class Province:
- def __init__(self,name):
- self.name = name
- country = "中国"
- hn = Province('河南')
- hb = Province('河北')
- sd = Province('山东')
- hlj = Province('黑龙江')
节省内存空间:
- class Province:
- country = "中国"
- def __init__(self,name):
- self.name = name
- hn = Province('河南')
- hb = Province('河北')
- sd = Province('山东')
- hlj = Province('黑龙江')
一般情况:自己访问自己的字段
规则:普通字段只能用对象访问,静态字段用类访问(可以使用对象访问)。
静态字段在代码加载时已经创建。
- print(hn.name)
- print(Province.country)
普通方法、静态方法、类方法
- class Province:
- country = "中国"
- def __init__(self,name):
- self.name = name
- #普通方法,由对象调用执行(方法属于类)
- def show(self):
- # print(self.name)
- print("河北")
- #静态方法,由类调用执行(当方法内部不需要对象中封装的对象)
- @staticmethod
- def f1(arg1,arg2):
- print(arg1,arg2)
- #类方法(静态方法的一种,至少一个参数,自动传递类名),由类调用执行
- @classmethod
- def f2(cls):
- print(cls)
- Province.f1(111,222)
- Province.f2()
- obj = Province("河南")
- obj.show()
- 输出:
- 111 222
- <class '__main__.Province'>
- 河北
单例模式:类方法。
所有的方法属于类:
1、普通方法,至少一个self,对象执行。
2、静态方法,任意参数,类执行(可以对象执行)。
3、类方法,至少一个cls,类执行(可以对象执行)。
类成员属性
- class Pager:
- def __init__(self,all_count):
- self.all_count = all_count
- def all_pager(self):
- a1,a2 = divmod(self.all_count,10)
- if a2 == 0:
- return a1
- else:
- return a1 + 1
- p = Pager(101)
- ret = p.all_pager() #方法
- print(ret)
- class Pager:
- def __init__(self,all_count):
- self.all_count = all_count
- @property
- def all_pager(self):
- a1,a2 = divmod(self.all_count,10)
- if a2 == 0:
- return a1
- else:
- return a1 + 1
- p = Pager(101)
- ret = p.all_pager
- print(ret)
- class Pager:
- def __init__(self,all_count):
- self.all_count = all_count
- #获取
- @property
- def all_pager(self):
- a1,a2 = divmod(self.all_count,10)
- if a2 == 0:
- return a1
- else:
- return a1 + 1
- #设置
- @all_pager.setter
- def all_pager(self,value):
- print(value)
- #删除
- @all_pager.deleter
- def all_pager(self):
- print("del all_pager")
- p = Pager(101)
- ret = p.all_pager
- print(ret)
- p.all_pager = 111
- del p.all_pager
- 输出:
- 11
- 111
- del all_pager
属性:具有方法的写作形式,具有字段访问形式。
- class Pager:
- def __init__(self,all_count):
- self.all_count = all_count
- def f1(self):
- return 123
- def f2(self,value):
- print(value)
- def f3(self):
- print("del")
- foo = property(fget=f1,fset=f2,fdel=f3)
- p = Pager(101)
- ret = p.foo
- print(ret)
- p.foo = "alex"
- del p.foo
- 输出:
- 123
- alex
- del
成员修饰符
- class Foo:
- #__cc私有静态字段
- __cc = 123
- def __init__(self,name,age):
- self.name = name
- #__age私有普通字段
- self.__age = age
- def f1(self):
- print("f1:"+self.name)
- print(self.__age)
- def f3(self):
- print(Foo.__cc)
- @staticmethod
- def f4():
- print("staticmethod:",Foo.__cc)
- class Bar(Foo):
- def f2(self):
- print(self.name)
- #私有普通字段 不能访问
- # print(self.__age)
- obj = Foo('alex',19)
- print(obj.name)
- # print(obj.age) 不能外部调用
- # print(Foo.__cc) 不能外部调用
- obj.f1()
- obj.f3()
- Foo.f4()
- obj1 = Bar("tom",20)
- obj1.f2()
- obj1.f1()
私有:只有类本身成员内部可以访问。
注意:特殊访问私有字段的方法(_类名__xxx)。
print(obj._Foo__age)
特殊成员
- class Foo:
- #构造方法
- def __init__(self):
- print("init")
- #析构方法
- def __del__(self):
- print("del")
- def __call__(*args,**kwargs):
- print("call")
- p = Foo()
- #获取类名
- print(p.__class__)
- #执行call方法
- p()
- #执行call方法
- Foo()()
- 输出:
- init
- <class '__main__.Foo'>
- call
- init
- call
- del
- del
- class Foo:
- #构造方法
- def __init__(self,name,age):
- self.name = name
- self.age = age
- #析构方法
- def __del__(self):
- pass
- def __call__(*args,**kwargs):
- print("call")
- def __str__(self):
- return "%s----%d" %(self.name,self.age)
- obj = Foo("alex",34)
- print(obj)
- obj2 = Foo("eric",23)
- print(obj2)
- 输出:
- alex----34
- eric----23
- obj1 = Foo('alex',23)
- obj2 = Foo('eric',21)
- #获取对象中封装的数据
- ret = obj1.__dict__
- print(ret)
- 输出:
- {'age': 23, 'name': 'alex'}
- class Foo:
- #构造方法
- def __init__(self,name,age):
- self.name = name
- self.age = age
- #析构方法
- def __del__(self):
- pass
- def __call__(*args,**kwargs):
- print("call")
- def __str__(self):
- return "%s----%d" %(self.name,self.age)
- def __getitem__(self,item):
- print("getitem")
- def __setitem__(self, key, value):
- print("setitem")
- def __delitem__(self, key):
- print("delitem")
- obj = Foo('alex',18)
- #call方法
- obj()
- obj["abc"] = 111
- del obj['abc']
- 输出:
- call
- setitem
- delitem
- class Foo:
- #构造方法
- def __init__(self,name,age):
- self.name = name
- self.age = age
- def __getitem__(self,item):
- print(type(item))
- if type(item) == str:
- pass
- else:
- print(item.start)
- print(item.stop)
- print(item.step)
- print("getitem")
- def __setitem__(self, key, value):
- print(type(key),type(value))
- print("setitem")
- def __delitem__(self, key):
- print(type(key))
- print("delitem")
- obj = Foo('alex',14)
- #getitem
- ret1 = obj[1:4:2]
- #getitem
- ret2 = obj['abc']
- obj[1:3] = [11,22,33]
- del obj[1:5]
- 输出:
- <class 'slice'>
- 1
- 4
- 2
- getitem
- <class 'str'>
- getitem
- <class 'slice'> <class 'list'>
- setitem
- <class 'slice'>
- delitem
- class Foo:
- """
- def __iter__(self):
- print("iter")
- return iter([11,22,333])
- """
- def __iter__(self):
- yield 1
- yield 2
- obj = Foo()
- for item in obj:
- print(item)
- 输出:
- """
- iter
- 11
- 22
- 333
- """
- 1
- 2
- class Bar:
- pass
- class Foo():
- pass
- obj = Foo()
- #查看某个对象是不是由某个类创建
- ret = isinstance(obj,Foo)
- ret2 = isinstance(obj,Bar)
- print(ret)
- print(ret2)
- 输出:
- True
- False
isinstance和issubclass
- class Bar:
- pass
- class Foo(Bar):
- pass
- obj = Foo()
- #查看某个对象是不是由某个类创建
- ret = isinstance(obj,Foo)
- ret2 = isinstance(obj,Bar) #obj类型和obj类型的父类
- print(ret)
- print(ret2)
- #查看某个类是不是另一个类的子类
- ret3 = issubclass(Bar,Foo)
- ret4 = issubclass(Foo,Bar)
- print(ret3)
- print(ret4)
- 输出:
- True
- True
- False
- True
继承super
- class C2(C1):
- def f1(self):
- #执行C1中的f1
- super(C2,self).f1() #C1.f1(self)
- print('c2.f1')
- obj = C2()
- #默认执行C2中的f1
- obj.f1()
- 输出:
- c1.f1
- c2.f1
有序字典
- class MyDict(dict):
- def __init__(self):
- self.li = []
- super(MyDict,self).__init__()
- def __setitem__(self,key,value):
- self.li.append(key)
- super(MyDict,self).__setitem__(key,value)
- def __str__(self):
- temp_list = []
- for key in self.li:
- value = self.get(key)
- temp_list.append("'%s':%s"%(key,value))
- temp_list = "{" + ",".join(temp_list) + "}"
- return temp_list
- obj = MyDict()
- obj['k1'] = 123
- obj['k2'] = 456
- print(obj)
单例模式
单例模式用来创建单个实例。
- class Foo:
- instance = None
- def __init__(self,name):
- self.name = name
- @classmethod
- def get_instance(cls):
- #cls类名
- if cls.instance:
- print("已经创建对象")
- return cls.instance
- else:
- #创建对象
- obj = cls('alex')
- print("新创建对象")
- cls.instance = obj
- return obj
- obj = Foo.get_instance()
- obj1 = Foo.get_instance()
- print(id(obj),id(obj1))
- 输出:
- 新创建对象
- 已经创建对象
- 7225864 7225864
异常处理
- while True:
- num1 = input("num1:")
- num2 = input("num2:")
- try:
- num1 = int(num1)
- num2 = int(num2)
- result = num1 + num2
- except Exception as ex: #捕获所有错误
- print(ex)
- except ValueError as ve: #捕获ValueError
- print(ve)
- except IndexError as ie: #捕获IndexError
- print(ie)
- except Exception as ex: #捕获所有错误
- print(ex)
- try:
- pass
- except ValueError as ve:
- print(ve)
- except Exception as ex:
- print(ex)
- finally: #不管有无错误都执行finally
- pass
- try:
- raise ValueError('主动触发错误')
- pass
- except ValueError as ve:
- print("ValueError",ve)
- except Exception as ex:
- print(ex)
- finally: #不管有无错误都执行finally
- pass
- 输出:
- ValueError 主动触发错误
断言
- assert 1 == 1
- #报错
- assert 1 == 2
posted on 2017-02-08 12:31 yinshoucheng 阅读(376) 评论(0) 编辑 收藏 举报