您的位置:首页 > 其它

面向对象及相关

2016-06-29 14:31 417 查看
一、isinstance(obj, cls)

检查是否obj是否是类 cls 的对象

class Foo(object):
pass

obj = Foo()

isinstance(obj, Foo)


二、issubclass(sub, super)

检查sub类是否是 super 类的派生类

class Bar():
pass
class Foo(Bar):
pass

obj = Foo()
ret = isinstance(obj,Foo)
ret1 = issubclass(Foo,Bar)
ret3 = isinstance(obj,Bar)
print(ret) #True
print(ret1)#True
print(ret3) #True


三、异常处理

1、异常基础

在编程过程中为了增加友好性,在程序出现bug时一般不会将错误信息显示给用户,而是现实一个提示的页面,通俗来说就是不让用户看见大黄页!!!

try:
pass
except Exception,ex:
pass


需求:将用户输入的两个数字相加

实例:IndexError

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_str = "{" + ",".join(temp_list) + "}"
return temp_str

obj = MyDict()
obj['k1']  = 123
obj['k2'] = 456
print(obj)


View Code

六、设计模式之单例模式



模式特点:保证类仅有一个实例,并提供一个访问它的全局访问点。

说明: 为了实现单例模式费了不少工夫,后来查到一篇博文对此有很详细的介绍,而且实现方式也很丰富,通过对代码的学习可以了解更多Python的用法。以下的代码出自GhostFromHeaven的专栏,地址:http://blog.csdn.net/ghostfromheaven/article/details/7671853。不过正如其作者在Python单例模式终极版所说:

方法一:

class Foo:
instance = None
def __init__(self,name):
self.name = name
@classmethod
def get_instance(cls):
#cls类名
if cls.instance:
return cls.instance
else:
obj = cls('alex')
cls.instance = obj
return obj
def __str__(self):
return self.name

obj1 = Foo.get_instance()
print(obj1)
obj2 = Foo.get_instance()
print(obj2)
obj = Foo('jason')
print(obj)


方法二:

#方法1,实现__new__方法

#并在将一个类的实例绑定到类变量_instance上,

#如果cls._instance为None说明该类还没有实例化过,实例化该类,并返回

#如果cls._instance不为None,直接返回cls._instance

class Singleton(object):
def __new__(cls, *args, **kw):
if not hasattr(cls, '_instance'):
orig = super(Singleton, cls)
cls._instance = orig.__new__(cls, *args, **kw)
return cls._instance

class MyClass(Singleton):
a = 1

one = MyClass()
two = MyClass()
two.a = 3
print(one) #<__main__.MyClass object at 0x10238d048>
print(two) #<__main__.MyClass object at 0x10238d048>
print(one.a) #3
print(two.a) #3


参考(goF设计模式):

《大话设计模式》Python版代码实现 http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html
Java实现 http://www.runoob.com/design-pattern/design-pattern-tutorial.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: