目录
1. 类的创建及实例化
2. 继承
3. 多态
4. 静态方法
5. 类方法
6. 属性方法
7. 类的专有方法
8. 反射
一、类的创建以及实例化
1 class Role(object): 2 n = 123 #类变量 3 n_list = [] 4 5 def __init__(self,name,role,weapon,life_value=100,money=15000): 6 #构造函数 7 #在实例化时做一些类的初始化工作 8 self.name = name #实例变量(静态属性),作用域为实例本身 9 self.role = role 10 self. weapon = weapon 11 self.__life_value = life_value # __ 私有属性 12 self.money = money 13 14 def __del__(self): 15 #析构函数:在实例释放或销毁时自动执行,用于做一些收尾工作,如关闭一些数据库连接、关闭打开的临时文件 16 print("%s彻底死了。。。"%self.name) 17 18 def show_status(self): #私有属性要通过内部的方法来访问 19 print("name:%s weapon:%s life_value:%s"%(self.name,self.weapon,self.__life_value)) 20 21 def shot(self): #方法(动态属性) 22 print("shooting...") 23 24 def got_shot(self): 25 self.__life_value -= 50 26 print("%s got shot..."%self.name) 27 28 def buy_gun(self,gun_name): 29 print("just bought %s"%gun_name) 30 31 def __own(self): #私有方法 32 print("own") 33 34 # print(Role.n) 35 # Role. n = 4 36 # print(Role.n)1 37 38 r1 = Role('Ztian','police','AK47') #实例化出一个对象。将r1赋给self参数 39 r1.got_shot() #Role.got_shot(r1) 40 r1.show_status() 41 r1.n_list = [1] 42 print(r1.n_list) 43 print(Role.n_list) 44 del r1 45 r2 = Role('Laowang','police','AK47') #实例化出一个对象。将r1赋给self参数 46 r2.got_shot()
1. __init__()方法
__init__()方法叫做构造方法,当类进行实例化时会自动调用这个函数,进行初始化。
参数self指向类的一个实例。
1 r1 = Role('Ztian','police','AK47') #实例化出一个对象。将r1赋给self参数
以上类在进行实例化时首先会在内存中开辟一块空间并指向变量r1,然后调用类中的__init__()方法,相当于执行了 Role.__init__(r1,'ztian','police',’AK47’) ,将参数'ztian','police','AK47'与刚刚开辟的空间r1关联起来,然后就可以通过self.name等来调用。
2. __del__()方法
__del__()方法叫做析构方法,在实例释放或销毁时自动执行,用于做一些收尾工作,如关闭一些数据库链接、关闭打开的临时文件等。
3. 私有属性或私有方法
在属性名或方法名前加“__”,对应属性和方法就变为私有属性或私有方法,只能通过类内部的方法来访问。
二、继承
原有的类称为父类,新的类称为子类,子类继承了父类所有的属性和方法,同时还可以定义自己的属性和方法。
1 # class People: #经典类 2 class People(object): #新式类 3 4 def __init__(self,name,age): 5 self.name = name 6 self.age = age 7 self.friends = [] 8 9 def eat(self): 10 print("%s is eating..."%self.name) 11 12 def sleep(self): 13 print("%s is sleeping..."%self.name) 14 15 class Relation(object): 16 def make_friends(self,obj): 17 print("%s is making friends weith %s"%(self.name,obj.name)) 18 self.friends.append(obj) 19 20 class Man(People,Relation): #多继承顺序,从左到右 21 def __init__(self,name,age,money): 22 # People.__init__(self,name,age) #经典类 23 super(Man,self).__init__(name,age) #新式类写法,同People.__init__(self,name,age) 24 self.money = money 25 print('一出生就有%s多块钱'%self.money) 26 27 def piao(self): 28 print("%s is piaoing..."%self.name) 29 30 def sleep(self): #重构 31 People.sleep(self) 32 print("%s is sleeping man..."%self.name) 33 34 35 class Woman(People,Relation): 36 def get_birth(self): 37 print("%s is borning..."%self.name) 38 39 40 41 42 m1 = Man('Laowang',23,10) 43 # m1.eat() 44 # m1.piao() 45 # m1.sleep() 46 w1 = Woman('zz22) 47 # w1.get_birth() 48 49 m1.make_friends(w1) 50 print(m1.friends[0].name)
1. 新式类和经典类
继承顺序不同:在py2中,经典类是按深度优先继承,新式类是按广度优先继承;在py3中,经典类和新式类都是按广度优先继承。
继承的代码写法不同:
1 super(Man,self).__init__(name,age) #新式类写法,同People.__init__(self,name,age)
2. 多继承
1 class Man(People,Relation): #多继承顺序,从左到右 2 def __init__(self,name,age,money): 3 # People.__init__(self,name,age) #经典类 4 super(Man,self).__init__(name,age) #新式类写法,同People.__init__(self,name,age) 5 self.money = money
三、多态
多态:一种接口,多种形态。
1 class Animal(object): 2 def __init__(self, name): 3 self.name = name 4 5 def talk(self): 6 pass 7 8 @staticmethod 9 def animal_talk(obj): 10 obj.talk() 11 12 class Cat(Animal): 13 def talk(self): 14 print('%s: 喵喵喵!' % self.name) 15 16 17 class Dog(Animal): 18 def talk(self): 19 print('%s: 汪!汪!汪!' % self.name) 20 21 22 # def animal_talk(obj): # 一个接口,多种形态 23 # obj.talk() 24 25 26 c1 = Cat('小一') 27 d1 = Dog('小二') 28 29 # animal_talk(c1) 30 # animal_talk(d1) 31 Animal.animal_talk(c1) 32 Animal.animal_talk(d1)
四、静态方法
通过装饰器@staticmethod使一个类的方法变为静态方法,该方法不可以访问实例变量和类变量,相当于与类本身已经没什么关系了,但还需要通过类名来调用这个方法。
1 class Dog(object): 2 def __init__(self,name): 3 self.name = name 4 5 @staticmethod #静态方法,使该方法与类没什么关系了 6 def eat(self,food): 7 print("%s is eating %s"%(self.name,food)) 8 9 d = Dog("xiaoyi") 10 d.eat(d,"包子")
注意,静态方法调用的时候, d.eat(d,"包子") 传入了self对应的参数d。
五、类方法
通过装饰器@classmethod来实现。类方法只能访问类变量,不能访问实例变量。
1 class Dog(object): 2 3 n=333 4 5 def __init__(self,name): 6 self.name = name 7 8 # @staticmethod #静态方法,使该方法与类没什么关系了 9 @classmethod #类方法只能使用类变量不能使用实例变量 10 def eat(self,food): 11 # print("%s is eating %s"%(self.name,food)) 12 print("%s is eating %s"%(self.n,food)) 13 14 d = Dog("xiaoyi") 15 d.eat("包子")
六、属性方法
通过装饰器@property把一个方法变成一个静态属性。
class Dog(object): def __init__(self,name): self.name = name self.__food = None @property #把一个方法变成一个静态属性 def eat(self): print("%s is eating %s"%(self.name,self.__food)) @eat.setter def eat(self,food): print("set to food:",food) self.__food = food @eat.deleter def eat(self): del self.__food print("删完了") d = Dog("xiaoyi") d.eat d.eat = "包子" d.eat del d.eat d.eat
通过装饰器@eat.setter和@eat.deleter重写属性方法,可以修改属性方法的值和删除属性。
七、类的专有方法
__doc__:表示类的描述信息。
__module__:表示当前操作的对象所属的模块是什么
__class__:表示当前操作的对象所属的类是什么。
__init__:构造方法。
__del__:析构方法。
__call__:后面加括号即可触发执行。
__dict__:查看类或对象中的所有成员。
__str__:打印对象时,默认输出该方法的返回值。
__getitem__\__setitem__\__delitem__:用于索引操作,如字典。
八、反射
通过字符串映射来修改程序运行时的状态、属性、方法。
1 def hasattr(*args, **kwargs): # real signature unknown 2 """ 3 Return whether the object has an attribute with the given name. 4 5 This is done by calling getattr(obj, name) and catching AttributeError. 6 """ 7 pass
1 def getattr(object, name, default=None): # known special case of getattr 2 """ 3 getattr(object, name[, default]) -> value 4 5 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. 6 When a default argument is given, it is returned when the attribute doesn't 7 exist; without it, an exception is raised in that case. 8 """ 9 pass
1 def setattr(x, y, v): # real signature unknown; restored from __doc__ 2 """ 3 Sets the named attribute on the given object to the specified value. 4 5 setattr(x, 'y', v) is equivalent to ``x.y = v'' 6 """ 7 pass
1 def delattr(x, y): # real signature unknown; restored from __doc__ 2 """ 3 Deletes the named attribute from the given object. 4 5 delattr(x, 'y') is equivalent to ``del x.y'' 6 """ 7 pass
1 class Dog(object): 2 3 def __init__(self,name): 4 self.name = name 5 6 def eat(self,food): 7 print("%s is eating %s..."%(self.name,food)) 8 9 def bulk(self): 10 print("%s is yelling..."%self.name) 11 12 d = Dog("XiaoYi") 13 14 choice = input(">>:").strip() 15 16 # print(hasattr(d,choice)) #判断一个对象里是否有对应的字符串的方法映射 17 # 18 # print(getattr(d,choice)) #根据字符串去获取对象里对应的方法的内存地址 19 # 20 # # getattr(d,choice)() 21 22 if hasattr(d,choice): 23 func = getattr(d,choice) 24 func("京酱肉丝") 25 else: 26 # setattr(d,choice,bulk) 27 # func = getattr(d,choice) 28 # func(d) 29 # d.bulk(d) 30 setattr(d,choice,None) #通过字符串设置新的属性或方法 31 print(getattr(d,choice))