python之day8

一,作业    

  要点
        1 封装,对象中嵌套对象
        2 pickle,load:切记,一定要导入相关类


二 上节内容回顾和补充


    面向对象基本知识:
        1 类和对象的关系
        2 三大特性:
            封装
            继承
    面向对象三大特性:
        3 多态
            def func(arg):
                print(arg)
            func(1)
            func('alex')
            func([11,22,33])
            
            C#/java
            def func(int arg):
                print(arg)
            func(123)
            func("alex") #报错
            看图


三 面向对象中的成员


    字段
        静态字段
        普通字段
        ps:静态字段代码加载时,已经创建
        class Foo:
            #字段(静态字段)
            CC = 123
            def __init__(self):
                #字段(普通的字段)    保存在对象里
                self.name = 'alex'
            
            def show(self):
                print(self.name)
            
            #一般情况:自己访问自己的字段
            #规则:
            #普通字段只能对象访问
            #静态字段用类访问(万不得已的时候可以使用访问)

    方法
        所有的方法属于类
        普通方法,由对象去调用执行(方法属于类)至少一个self
        静态方法,参数可有可无 在上面加一个@staticmethod 可以由类调用执行(不需要再用对象来调用了)
        类方法,静态方法的特殊形式 必须有参数cls --》代表类名
        

class Province():
    country  = "中国"
    def __init__(self,name):
        self.name = name

    @staticmethod
    def f1():
        print('北京')

    @classmethod
    def f2(cls):
        print(cls)
hn = Province("河南")
hb = Province("河北")
sd = Province("山东")
Province.f1()
Province.f2()


    属性
        不伦不类的东西
        具有方法的写作形式,具有字段访问形式

例1

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')

obj = Pager(101)
# ret = obj.all_pager
# print(ret)
obj.all_pager = 111

del obj.all_pager

 例二

class Foo:
    def f1(self):
        return "f1"

    def f2(self,value):
        print(value)

    def f3(self):
        print("f3")

    foo = property(f1,f2,f3)

f = Foo()
ret = f.foo
print(ret)

f.foo = "f2"

del f.foo

四 成员修饰符

  私有:
      __name 是私有字段 类内部可以访问 类外部不能访问
      私有的 继承也不能用
    
    公有:
        都可以访问
    

  PS:不到万不得已不用再外部强制访问

私有字段:

class Foo:
    __cc = "aaa"
    def __init__(self,name):
        self.__name = name

    def f1(self):
        print(self.__name)

    def f2(self):
        print(Foo.__cc)

f = Foo("alex")
f.f1()
f.f2()

 私有方法:

class Foo:
    def __init__(self,name):
        self.name = name

    def __f1(self):
        print(self.name)

    def f11(self):
        f1 = self.__f1()

    @staticmethod
    def __f2():
        print("f2")

    @staticmethod
    def f22():
        f2 = Foo.__f2()


f = Foo("alex")
f.f11()
f.f22()

五 特殊成员    


    __init__  构造方法
    __del__   析构方法
    __dict__  所有的字段信息 获取对象中封装的数据,类也有
    __doc__
    __call__    对象后面加()调用这个方法
    __setitem__    对象后面加[] 进行传递
    __getitem__  对象后面加[] 获取
    __delitem__   del obj['k1']
    __str__     print 对象

例一:

class Foo:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __call__(self):
        print('call')

    def __str__(self):
        return "%s-%d" % (self.name,self.age)

    def __getitem__(self, item):
        print(item.start)
        print(item.stop)
        print(item.step)


    def __setitem__(self, key, value):
        print('set')

    def __delitem__(self, key):
        print('del')

f = Foo("abc",12)
f()


f1 = Foo("alex",28)
f2 = Foo("eric",38)
print(f1,f2)
print(f1.__dict__['name'])



f['k1']
f['k1'] = 'v1'
del f['k1']

例二:

class Foo:
    def __getitem__(self, item):
        print(item.start)
        print(item.stop)
        print(item.step)

    def __setitem__(self, key, value):
        print(key.start)
        print(key.stop)
        print(key.step)


f = Foo()
f[1:2:1]
f[1:2:1] = 'aaa'

例三:

class Foo:
    def __iter__(self):
        yield 1
        yield 2

f = Foo()
for i in f:
    print(i)

    

六 面向对象 其他:

        - isinstance   判断这个对象 是不是这个类创建的
        - issubclass    判断是不是子类 前面是父类,后面是子类
        - 继承 2.7
        - 应用:
            自定义类型,对字典进行补充,有序字典
            源码的扩展

例一(调用父类中的同名函数用super)

class c1:
    def f1(self):
        print('c1.f1')

class c2(c1):
    def f1(self):
        super(c2,self).f1()
        print('c2.f2')


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

f = Mydict()
f['k1'] = 1
f['k2'] = 2
print(f)


           

七 异常处理:

    代码块
    try:
        raise Exception('主动错误')
        pass
    except ValueError as ex:
        print(ex)
    except Exception as ex:
        print(ex)
    else:
        pass
    finally:
        pass

    断言:
        assert 1 == 1
        #assert 1 == 2

八 设计模式之单例模式  

  单例模式:类似于线程池,不停的调用同一个函数

例一:

class Foo:
    instance = None

    def __init__(self,name):
        self.name = name

    @classmethod
    def get_instance(cls):
        if cls.instance:
            return cls.instance
        else:
            obj = cls("alex")
            cls.instance = obj
            return obj

f1 = Foo.get_instance()
print(f1)

  

原文地址:https://www.cnblogs.com/aaron-shen/p/5617705.html