类-多态、类成员、类特殊成员、类属性、成员属性 公有私有、执行父类、有序字典、单例模式

 一、类-多态

 

#python可以传递多个参数,任何数据
def func(arg):
    print(arg)

func(1)
func("alex")
func([11,22,33])

# #c#/java 必须要指定类型  不支持多态,通过继承来实现多态

 

 

二、类成员

字段:
静态字段
普通子弹
PS:静态字段在代码加载的时候已经创建
class Foo:
    #字段(静态字段)  保存在类中
    CC = 123
    def  __init__(self):
        #字段(普通字段) 保存在对象中
        self.name = "alex"

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

class Province:
    country = "中国"
    def __init__(self,name):
        self.name = name
#一般情况,自己访问自己的字段
#普通字段只能用对象访问
#静态字段用类访问(万不得已用对象访问)
hn = Province("河南")
print(hn.name)
print(Province.country)
print(hn.country)

#以下为执行结果:

 河南
 中国
 中国

方法
所有方法属于类
1、普通方法:至少一个self,对象执行
2、静态方法:任意参数, 类执行
3、类方法:至少一个cla,类执行
class Province:
    country = "中国"
    def __init__(self,name):
        self.name = name
    #普通方法,由对象调用执行
    def show(self):
        print(self.name)
    #静态方法,由类调用
    @staticmethod
    def  f1(arg1,arg2):
        print(arg1,arg2)
    #类方法, 由类执行
    @classmethod
    def f2(cls):
        print(cls)

    def f3(self):
            return  self.name[1]


obj = Province("河南")
obj.show()

Province.f1(1111,2222)
Province.f2()

obj=Province("alex")
print(obj.f3())

#以下为执行结果:
河南
1111 2222
<class '__main__.Province'>
l

 

三、类的特殊成员

#__init__
#__del__
#__call__
#__class__
class Foo:
    def __init__(self):  #构造方法
       print("init")
    #析构方法
    def __del__(self):   #内存回收前,自动执行p。
        pass
    def __call__(self):
        print("call")

p= Foo()
print(p.__class__)  #显示所在类
p()
Foo()()  #init和call方法一起执行

#以下为执行结果:
init
<class '__main__.Foo'>
call
init
call

 

#__dict__
class Foo:
    def __init__(self,name,age):  #构造方法
#        print("init")
        self.name=name
        self.age=age

# obj = Foo()
# print (obj1)

obj1=Foo("alex",38)
obj2=Foo("asdf",22)
#获取对象中封装的数据
ret= obj1.__dict__
print(ret)

#以下为执行结果:
{'age': 38, 'name': 'alex'}

 

#__add__

class Foo:
    def __init__(self,name,age):  #构造方法
#        print("init")
        self.name=name
        self.age=age
    def __add__(self, other):
        return "%s - %s" % (self.name, other.age)

obj1=Foo("alex",38)
obj2=Foo("asdf",22)

ret=obj1+obj2
print(ret)
#以下为执行结果:
alex - 22


#__str__
class Foo:
    def __init__(self, name, age):  # 构造方法
        self.name = name
        self.age = age
    def __str__(self):  # 类返回值
        return "%s - %s" % (self.name, self.age)

obj1=Foo("alex",38)
print (obj1)

#以下为执行结果
alex - 38

 

#__getitem__

#__setitem__
#__delitem__


class Foo:
    def __init__(self, name, age):  # 构造方法
        self.name = name
        self.age = age

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

        print('getitem')
        return 123

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

    def __delitem__(self, key):
        print("delitem")

obj = Foo('alex',23)
ret =obj[1:4:2]
obj[1:2:2] =111

#以下为执行结果:
<class 'slice'> slice(1, 4, 2)
1
4
2
getitem
setitem
1
2
2

 

四、属性   使用属性的两种方式

 

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)
# p.all_count #字段
# result=p.all_pager()  #方法
# print(result)
ret=p.all_pager
print (ret)
p.all_pager=102
del p.all_pager

#以下为执行结果:
11
102
del all_pager

 

class Pager:
    def __init__(self,all_count):
        self.all_count=all_count
    def f1(self):
        return 123


    def f2(self,value):
        pass


    def f3(self):
        return  234
    foo = property(fget=f1,fset=f2,fdel=f3)
p=Pager(101)
result=p.foo
print(result)
p.foo="alex"
del p.foo
#以下为执行结果:
123

 

五、成员修饰符

#正常都是共有的
#私有普通字段   加俩下划线    self.__name=name  只有自己本身成员内部可访问继承累后也无法执行

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

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


class Bar(Foo):
    def f2(self):
        print(self.__name)

obj= Foo("alex")
print (obj.__name)


#私有的静态字段静态字段
class Foo:
    __cc="123"
    def __init__(self,name):
        self.__name=name
    def f1(self):
        print (self.__name)
    @staticmethod
    def f3(self):
        print(Foo.__cc)

Foo.f3("alex")
obj=Foo("alex")
print(obj._Foo__name)        #外部访问私,建议不要这么用

#以下为执行结果:
init
<class '__main__.Foo'>
call
init
call

 

六、判断是否是子类父类

 

class Bar:
    pass

class Foo:
    pass


obj = Foo()
#查看obj是否是bar(可以是obj类型的父类) 的实例
ret =isinstance(obj,Bar)
print (ret)

#判断是是子类
ret = issubclass(Bar,Foo)
print (ret)
#以下为执行结果:
False
False

 

七 、super 执行父类

#执行父类的方法

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

class C2(C1):
    def f1(self):
        #主动执行父类的f1方法
        super(C2,self).f1()
        print('c2,f1')

#        C1.f1(self)  建议用super
obj=C2()
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_str ="{" + ",".join(temp_list) +"}"
        return  temp_str

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

#以下为执行结果:
{'k1':123,'k2':456}

 

九、异常处理

格式:

# try:
# pass
# except Exception,ex:
# pass

十、设计模式单例模式

#用来创建单个实例
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

#obj= Foo("alex")
obj1= Foo.get_instance()
print(obj1)
obj2= Foo.get_instance()
print(obj2)

#以下为执行结果
<__main__.Foo object at 0x00000093C2C84278>
<__main__.Foo object at 0x00000093C2C84278>

 

posted @ 2016-06-30 14:38  不是云  阅读(190)  评论(0编辑  收藏  举报