基础知识
编程:语法+数据结构+算法
编程范式:
面向过程,step by step top-down language
面向对象oop,世界万物,皆可分类,皆为对象
特性
class –实例化–> object
实例化:把类变成具体对象的过程
封装:数据隐藏
把一些功能的实现细节不对外暴露
继承:代码复用
组合
单继承
多继承
py2
- 经典类:深度优先来继承的
- 新式类:广度优先来继承的 class Foo(object)
py3
- 经典类和新式类都是按照广度优先来继承的
多态:接口重用
一个接口,多种实现
类:
1. 属性:
1. 类变量 大家共用属性,节省内存开销
2. 实例变量(静态属性):作用域是实例本身
3. 私有属性 __开头
2.方法(动态属性)
1. 构造函数:init 实例化时做类的初始化工作
2. 析构函数:del 释放,销毁对象时执行,通常用于收尾工作,如关闭数据库连接,关闭临时文件
3. 私有方法 __开头
4. 静态方法:staticmethod与类没什么关系,只是名义上数据
5. 类方法:classmethod 只能访问类变量,不能访问实例变量
6. 属性方法:property 把一个方法变成一个静态属性
编程原则:
1、不写重复代码
2、代码会经常变更,做到易读,易改
对象实例化:
数据拷贝
方法不拷贝
object.method 相当于 class.method(object)
类属性
class Dog(object): count = 0 # 类变量 lst = [] def __init__(self, name): # 构造函数 self.name = name # 实例变量 self.__age = 0 # 私有属性 def bark(self): # 方法 print("%s bark" % self.name) def __del__(self): # 析构函数 print("%s del" % self.name) # 实例化对象,并赋予实例变量,相当于局部变量 d1 = Dog("Tom") d2 = Dog("Alex") d3 = Dog("Jack") # 调用对象方法 d1.bark() # Tom bark d2.bark() # Alex bark d3.bark() # Jack bark # 修改类变量,相当于全局变量 d1.count = 12 d2.count = 12 d3.count = 12 print(Dog.count) #0 #类变量 没有被修改 print(d1.count) #12 print(d1.count) #12 print(d1.count) #12 d1.lst.append("d1") d2.lst.append("d2") d3.lst.append("d3") # 类变量 列表被修改了 print(Dog.lst) # ['d1', 'd2', 'd3'] print(d1.lst) # ['d1', 'd2', 'd3'] print(d2.lst) # ['d1', 'd2', 'd3'] print(d3.lst) # ['d1', 'd2', 'd3']
多态
class Animal(object): count = 1 def __init__(self, name): self.name = name self.__color = None def talk(self): pass @staticmethod # 静态方法 def animal_talk(animal): animal.talk() @classmethod # 类方法 def animal_sleep(cls): print(cls,cls.count) @property # 属性方法 def color(self): return self.__color @color.setter # 设置 def color(self, color): self.__color = color @color.deleter # 删除 def color(self): del self.__color class Cat(Animal): def talk(self): print("%s talking" % self.name) class Dog(Animal): def talk(self): print("%s talking" % self.name) cat = Cat("mimi") dog = Dog("jiji") Animal.animal_talk(cat) Animal.animal_talk(dog) Animal.animal_sleep() print(dog.color) dog.color = "red" print(dog.color) del dog.color
继承
# class People: #经典类 class People(object): # 新式类 def __init__(self, name, age): self.name = name self.age = age def sleep(self): print("%s is sleeping" % self.name) class Animal(object): def drink(self): print("%s drinking" % self.name) class Man(People, Animal): # 多继承 def __init__(self, name, age, money): People.__init__(self, name, age) # 等价于:super(Man, self).__init__(name, age) 新式类写法 self.money = money print("%s have money %s" % (name, money)) def work(self): print("%s is working" % self.name) def sleep(self): # 重载父类方法 People.sleep(self) # 调用父类方法 print("Man is sleeping") class Woman(People): def eat(self): print("%s is eating" % self.name) m = Man("Tom", 23, 2000) w = Woman("Jack", 24) m.sleep() # Tom is sleeping m.work() # Tom is working w.sleep() # Jack is sleeping w.eat() # Jack is eating m.drink() # Tom drinking
继承顺序
class A(object): pass # def __init__(self): # print("init A") class B(object): def __init__(self): print("init B") class C(A): pass # def __init__(self): # print("init C") class D(B): pass # def __init__(self): # print("init D") class E(C, D): pass # def __init__(self): # print("init E") e = E() # C -> A -> D -> B
类的特殊方法
class Dog(object): """类的描述信息""" def __init__(self,name): self.name = name self.data = {} def __call__(self): print("call") def __str__(self): #打印时触发 return self.name def __getitem__(self, item): # 像字典一样访问对象 print("getitem") return self.data.get(item) def __setitem__(self, key, value): # 设置值 print("setitem") self.data[key] = value def __delitem__(self, key): # 删除值 print("delitem") del self.data[key] print(Dog.__doc__) # 输出类的描述信息 dog = Dog("Tom") print(dog.__module__) # 输出模块 __main__ print(dog.__class__) # 输出类 <class '__main__.Dog'> dog() # 对象() 括号触发__call__ 方法 print(Dog.__dict__) #打印类所有属性,不包括实例属性 # {'__weakref__': <attribute '__weakref__' of 'Dog' objects>, # '__dict__': <attribute '__dict__' of 'Dog' objects>, # '__init__': <function Dog.__init__ at 0x00000000047B5BF8>, # '__doc__': '类的描述信息', # '__call__': <function Dog.__call__ at 0x00000000047B5C80>, # '__module__': '__main__'} print(dog.__dict__) # 打印实例所有属性,不包括类属性 # {'name': 'Tom'} print(dog) dog["dog1"] = "dogA" dog["dog2"] = "dogB" dog["dog3"] = "dogC" print(dog["dog1"]) print(dog["dog2"]) print(dog["dog3"]) print(dog.data) del dog["dog1"] del dog["dog2"] del dog["dog3"] print(dog.data)
类的本质
# python一切皆为对象,类类型也是对象 ,由type类实例化而来 # class Foo(): # def __init__(self, name, age): # self.name = name # self.age = age # # def talk(self): # print("%s is talking" % self.name) # # f= Foo("Alex", 23) # f.talk() # 等价于: def __init__(self, name, age): self.name = name self.age = age def talk(self): print("%s is talking" % self.name) Foo = type("Foo", (object,), {"__init__": __init__, "talk": talk}) f= Foo("Alex", 23) f.talk()
元类
class Foo(object): def __init__(self, name): self.name = name print("init") def __new__(cls, *args, **kwargs): print("new") return object.__new__(cls) # 继承父类的 new 方法 f = Foo("Tom") # new # init # 元类metaclass:就是类的类,所有类都源自type print(f.__class__) # <class '__main__.Foo'> print(Foo.__class__) # <class 'type'> a = 5 print(a.__class__) #<class 'int'> print(a.__class__.__class__) #<class 'type'> b = "name" print(b.__class__) # <class 'str'> print(b.__class__.__class__) # <class 'type'> def foo(): pass print(foo.__class__) #<class 'function'> print(foo.__class__.__class__) #<class 'type'>
反射
# 反射函数 """ hasattr() 检查成员 getattr() 获取成员 setattr() 设置成员 delattr() 删除成员 """ class Foo(object): def __init__(self): self.name = "Tom" def eat(self): print("eating") def talk(): print("talking") f= Foo() choice = input("输入>>") if hasattr(f, choice): # 判断对象是否有名称为choice 的属性 delattr(f, choice) # 删除对象属性 # func = getattr(f, choice) # 通过字符串获取对象函数地址 # func() else: setattr(f, "talk", talk) # 动态给对象增加新方法 f.talk() setattr(f, "age", 23) #给对象增加静态属性 print(f.age) print(f.name)