python面向对象
1 什么是类
定义:用来描述具有相同的属性和方法的对象的集合,它定义了该集合中每个对象所共有的属性和方法,对象是类的实例。
描述
1 class F(): 2 a = 10 3 def __init__(self, name, age): 4 self.name = name 5 self.age = age 6 7 def describe(self): 8 print("大家好,我是%s,今年%d岁了" % (self.name, self.age))
self参数为实例(对象)本身。
__init__(self)为构造方法,创建实例时自动执行。
类变量:a为类变量在整个实例化的对象中是公用的,它定义在类中且在函数体之外,类变量通常不作为实例变量使用。
实例化:创建一个类的实例,类的具体对象
对象:通过类定义的数据结构实例,对象包括两个数据成员(类变量和实例变量)和方法。
2 类的三大特性
2.1 封装
变量在类中的方法进行传递。
2.2 继承
继承:子类继承父类的字段和方法。
方法重写:当父类中的方法功能不能满足子类的需求,可在子类中重新写父类的方法。
如果在子类中需要父类中的构造方法,就要显示调用父类的构造方法,或者不重写父类的构造方法;子类不重写__init__,实例化子类时,会自动调用父类定义的__init__,如果重写了__inti__时,实力化子类就不会调用父类定义的__init__;如果重写了__inti__方法,要继承父类的构造方法,可以用以下两种方法:super(子类,self).__init__(参数1,参数2, ...)或者是:父类名.__init__(参数1,参数2, ...)
1 class F(): 2 a = 10 3 def __init__(self, name, age): 4 self.name = name 5 self.age = age 6 7 def describe(self): 8 print("大家好,我是%s,今年%d岁了" % (self.name, self.age)) 9 10 11 class S(F): 12 def __init__(self, name, age, sex): 13 F.__init__(self, name, age) 14 self.sex = sex 15 16 def describe(self): 17 # super(S, self).describe() 18 F.describe(self) 19 print("大家好,我是%s,%s生,今年%d岁了" % (self.name, self.sex, self.age)) 20 21 22 s = S("alex", 20, "男") 23 s.describe()
2.3 多态
多态:子类可继承多个父类
属性和方法查找顺序:从左到右,如果左右都继承同一个父类,那么先执行左右,再查找父类。、
Pycharm中找源码的快捷键:CTRL+鼠标左单击名称。也能通过左边的导航窗口进行查找。
3 类成员
3.1 字段
静态字段:属于类,可以通过对象访问,也可通过类访问,类属性。
普通字段:属于对象,只能通过对象访问。
3.3 方法
普通方法:保存在类中,由对象调用。
静态方法:保存在类中,由类直接调用,添加@staticmethod装饰器,self不是必须的,可由类直接调用。
类方法:静态方法情况下,self修改为cls,cls为当前类。
应用场景:如果对象中需要保存一些值,执行某功能时,需要使用对象中的值,使用普通方法;不需要任何对象中的值,使用静态方法。
@property:在普通方法之上,在对象调用方法时,不用加上括号。
1 class Province(): 2 3 # 静态字段,将对象中的重复的数据保存为一份,避免重复 4 country = "中国" 5 6 def __init__(self, name): 7 # 普通字段 8 self.name = name 9 print(Province.country) 10 11 # 静态方法,属于类 12 @staticmethod 13 def xo(): # 此处不需要传递self参数 14 print("静态方法") 15 16 # 将方法伪造成了一种字段 17 @property 18 def end(self): 19 temp = '%s nb' % self.name 20 print(temp) 21 22 # 类方法,属于类 23 @classmethod 24 def xxoo(cls): 25 print("classmethod",cls) 26 27 # 普通方法 28 def show(self): 29 print(self.name) 30 31 Province.xo() 32 Province.xxoo() 33 34 obj = Province("内蒙古") 35 obj.end 36 obj.show()
4 成员修饰符
私有成员:__属性或方法,对象无法直接访问,可通过类内部访问;私有属性不能通过类继承,但可通过父类的方法返回值间接访问。
1 class Foo(): 2 3 __v = '123' 4 5 def __init__(self, name, age): 6 self.name = name # 公有的 7 self.__age = age # 私有的,外部无法直接访问 8 9 def show(self): 10 print(self.__age) # 内部能访问 11 print(Foo.__v) 12 13 @staticmethod 14 def stat(): 15 return Foo.__v 16 17 def __f1(self): 18 print("私有方法") 19 20 def f2(self): 21 self.__f1() 22 23 class s(Foo): 24 25 def __init__(self, name): 26 self.name = 123 27 super(s,self).__init__() 28 29 def show(self): 30 print(self.__) 31 32 obj = Foo('alex', 18) 33 print(obj.name) 34 ret = Foo.stat() 35 print(ret) 36 obj.f2()
5 特殊成员
__init__,类()自动执行
__call__,对象(),类()()自动执行
__int__,int(对象)
__str__,str()方法
__add__,对象相加自动执行。
__del__,析构方法,对象被销毁时,自动执行。
__dict__,将对象中封装的所有内容通过字典的形式返回
__getitem__,索引时执行。
__setitem__,赋值时执行。
__delitem__,删除值执行。
__iter__,如果类中有__iter__方法,那么这个类创建的对象可进行迭代。
1 class Foo(): 2 3 def __init__(self): 4 print('init') 5 6 def __call__(self, *args, **kwargs): 7 print('call') 8 9 10 obj = Foo() 11 obj()
1 class Foo(): 2 3 def __init__(self): 4 print('init') 5 6 def __int__(self): 7 return 1 8 9 def __str__(self): 10 return 'alex' 11 12 obj = Foo() 13 # 自动执行对象的__int__方法,将结果返回给int对象 14 i = int(obj) 15 k = str(obj) 16 print(i) 17 print(k) 18 print(obj) # 自动执行Foo函数里面的__str__方法,首先str(),接着执行__str__
1 class Foo(): 2 3 def __init__(self, name, age): 4 self.name = name 5 self.age = age 6 7 def __add__(self, other): 8 return self.age + other.age 9 10 def __del__(self): 11 print('析构方法') # 对象销毁时,自动执行 12 13 obj1 = Foo('alex', 19) 14 obj2 = Foo('eiro', 66) 15 # 两个对象相加时,自动执行第一个对象的__add__方法,并且将第二个对象当作参传递进入 16 r = obj1 + obj2 17 print(r, type(r))
1 class Foo(): 2 3 def __init__(self, name, age): 4 self.name = name 5 self.age = age 6 7 8 obj = Foo('alex', 18) 9 d = obj.__dict__ 10 ret = Foo.__dict__ 11 print(d) 12 print(ret)
1 class Foo(): 2 3 def __init__(self, name, age): 4 self.name = name 5 self.age = age 6 7 def __getitem__(self, item): 8 return item + 10 9 10 def __setitem__(self, key, value): 11 print(key, value) 12 13 def __delitem__(self, key): 14 print(key) 15 16 li = Foo('alex', 18) 17 r = li[8] # 自动执行li对象的类中的__getitem__方法,8当作方法传递给item 18 print(r) 19 20 li[100] = 'alex' 21 22 del li[999]
1 class Foo(): 2 3 def __init__(self, name, age): 4 self.name = name 5 self.age = age 6 7 def __getitem__(self, item): 8 if type(item) == slice: 9 print("切片处理") 10 else: 11 print("索引处理") 12 13 def __setitem__(self, key, value): 14 print(key, value) 15 16 def __delitem__(self, key): 17 print(key) 18 19 li = Foo('alex', 18) 20 r = li[12334] # 自动执行li对象的类中的__getitem__方法,8当作方法传递给item 21 li[1:2:2]
1 class Foo(): 2 3 def __init__(self, name, age): 4 self.name = name 5 self.age = age 6 7 def __iter__(self): 8 return iter([1,2,3,4,5,6,6]) 9 10 li = Foo('alex', 18) 11 # 如果类中有__iter__方法,创建的对象是可迭代对象 12 # 对象.__iter__()返回值:迭代器 13 # for循环,迭代器,next 14 # 执行对象li类Foo中的__iter__方法,获取返回值。 15 # 循环上一步中返回的对象 16 for i in li: 17 print(i)
6 metaclass
python中,一切事都是对象。
实例是类的对象,类是type类的对象。type(Foo,),python中称对象都是以类的对象。
1 class MyType(type): 2 3 def __init__(self, *args, **kwargs): 4 # self = Foo 5 print("MyType中的init方法") 6 7 def __call__(self, *args, **kwargs): 8 # self = Foo 9 r = self.__new__() 10 11 # 创建类的时候,使用Mytype类创建。 12 class Foo(object, metaclass=MyType): 13 14 def __init__(self): 15 pass 16 17 def __new__(cls, *args, **kwargs): 18 retrun "创建对象" #obj是在new里面创建的 19 20 def func(self): 21 print('hello') 22 23 # 24 obj = Foo()
7 反射
通过字符串的形式操作对象中的成员。
getattr()
hasattr()
setattr()
delattr()
1 class Foo(): 2 3 def __init__(self, name, age): 4 self.name = name 5 self.age = age 6 7 def show(self): 8 return '%s-%s' % (self.name, self.age) 9 10 11 obj = Foo('alex', 18) 12 # b = 'name' 13 # print(obj.__dict__[b]) 14 15 # 去什么东西里面获取什么 16 # inp = input("->") 17 # r = getattr(obj, inp) 18 # print(r) 19 20 func = getattr(obj, 'show') 21 print(func()) 22 print(hasattr(obj, 'name')) 23 setattr(obj, 'k1', 'v1') # 24 print(obj.k1) 25 delattr(obj, 'k1')
1 # 模拟路由器 2 inp = input("请输入要查看的url:") 3 4 class Foo(): 5 6 def __init__(self): 7 self.name = 123 8 9 def f1(self): 10 return '首页' 11 12 def f2(self): 13 return '新闻' 14 15 def f3(self): 16 return '精华' 17 18 obj = Foo() 19 # if inp == 'f1': 20 # obj.f1() 21 # elif inp == 'f2': 22 # obj.f1() 23 # elif inp == 'f3': 24 # obj.f3() 25 # else: 26 # print('输入错误,没有执行') 27 28 if hasattr(obj, inp): 29 r = getattr(obj, inp) 30 print(r()) 31 else: 32 print('输入错误')
8 单例模式
例如连接数据库,数据库连接池的概念,明确某个类只有只有一个实例存在。
1 class Foo(): 2 3 def __init__(self, name, age): 4 self.name = name 5 self.age = age 6 7 def show(self): 8 print(self.name, self.age) 9 10 11 12 obj = Foo('alex', 18) # Foo类的实例,创建过程也是实例化过程 13 # 单例,单个实例,用于使用同一份实例(对象) 14 v = None 15 while True: 16 if v: 17 v.show() 18 else: 19 v = Foo('alex', 18) 20 v.show()
1 class Foo(): 2 3 __v = None 4 5 @classmethod 6 def get_instance(cls): 7 if cls.__v: 8 return cls.__v 9 else: 10 cls.__v = Foo() 11 return cls.__v 12 13 14 # 单例模式 15 obj1 = Foo.get_instance() 16 print(obj1) 17 obj2 = Foo.get_instance() 18 print(obj2)
浙公网安备 33010602011771号