原文地址: https://blog.csdn.net/fgf00/article/details/52479307 编辑:智能算法,欢迎关注! 上期我们一起学习了python中的类
今天我们继续学习python中类。
目录
1 类的高级方法
2 类的特殊成员方法
3 反射
4 异常处理
通过@staticmethod装饰器即可把其装饰的方法变为一个静态方法。普通的方法,可以在实例化后直接调用,并且在方法里可以通过self.调用实例变量或类变量,但静态方法是不可以访问实例变量或类变量的,一个不能访问实例变量和类变量的方法,其实相当于跟类本身已经没什么关系了,它与类唯一的关联就是需要通过类名来调用这个方法
1class Dog(object):
2 def __init__(self,name):
3 self.name = name
4 @staticmethod # 把eat方法变为静态方法
5 def eat(self):
6 print("%s is eating" %self.name)
7
8d = Dog("wangcai")
9d.eat()
上面的调用会出以下错误,
1TypeError: eat() missing 1 required positional argument: 'self'
说是eat需要一个self参数,但调用时却没有传递,没错,当eat变成静态方法后,再通过实例调用时就不会自动把实例本身当作一个参数传给self了。 想让上面的代码可以正常工作有两种办法
1class Dog(object):
2 def __init__(self,name):
3 self.name = name
4 @staticmethod # 把eat方法变为静态方法
5 def eat(self):
6 print("%s is eating" %self.name)
7
8d = Dog("wangcai")
9d.eat(d)
作用:只是相当于一个单纯函数,要传参数,就要把实例传进去。 如果说和类有关系,就是必须有类名去调用。调用不了类或实例中的任何属性
类方法通过@classmethod装饰器实现,类方法和普通方法的区别是: 类方法只能访问类变量,不能访问实例变量
1class Dog(object):
2 def __init__(self,name):
3 self.name = name
4 @classmethod
5 def eat(self):
6 print("%s is eating" % self.name)
7
8d = Dog("wangcai")
9d.eat()
执行报错如下,说Dog没有name属性,因为name是个实例变量,类方法是不能访问实例变量的
1AttributeError: type object 'Dog' has no attribute 'name'
此时可以定义一个类变量,也叫name,看下执行效果
1class Dog(object):
2 name = "哮天犬"
3 def __init__(self,name):
4 self.name = name
5 @classmethod
6 def eat(self):
7 print("%s is eating" % self.name)
8
9d = Dog("wangcai")
10d.eat()
属性方法的作用就是通过@property把一个方法变成一个静态属性 (函数–>变量)
1class Dog(object):
2 def __init__(self,name):
3 self.name = name
4 @property
5 def eat(self):
6 print("%s is eating" % self.name)
7
8d = Dog("wangcai")
9d.eat()
调用会出以下错误, 说NoneType is not callable, 因为eat此时已经变成一个静态属性了,不是方法了, 想调用已经不需要加()号了,直接d.eat就可以了
1TypeError: 'NoneType' object is not callable
正常调用如下
1d.eat
2# 输出
3wangcai is eating
但是有个问题,如果eat有其他参数,没法传参数。而且即使变成了静态属性,也没法像普通变量那样“=”赋值 怎么传参数呢?
1class Dog(object):
2 def __init__(self,name):
3 self.name = name
4 self.__food = None
5 @property
6 def eat(self):
7 print("%s is eating %s" %(self.name, self.__food))
8 @eat.setter # 赋值调用属性,调这个方法
9 def eat(self,food):
10 print("set to food:",food)
11 self.__food = food
12
13d = Dog("wangcai")
14d.eat
15d.eat = "baozi"
16d.eat
如果传多个参数,‘d.eat = “baozi1”,”baozi2”’,接收为元组形式。
1del d.eat
报错:
1AttributeError: can't delete attribute
默认不能删除,要删除也是在类里再写一个方法
1class Dog(object):
2 def __init__(self,name):
3 self.name = name
4 self.__food = None
5 @property
6 def eat(self):
7 print("%s is eating %s" %(self.name, self.__food))
8 @eat.setter # 赋值调用属性,调这个方法
9 def eat(self,food):
10 print("set to food:",food)
11 self.__food = food
12 @eat.deleter # 删除属性
13 def eat(self):
14 del self.__food
15 print("Delete the finished")
16
17d = Dog("wangcai")
18d.eat
19d.eat = "baozi"
20d.eat # 传完参数后调用
21del d.eat
22d.eat # 删完后调用
报错如下,说明已经删除了
1AttributeError: 'Dog' object has no attribute '_Dog__food'
好吧,把一个方法变成静态属性有什么卵用呢?既然想要静态变量,那直接定义成一个静态变量不就得了么?well, 以后你会需到很多场景是不能简单通过 定义 静态属性来实现的, 比如 ,你想知道一个航班当前的状态,是到达了、延迟了、取消了、还是已经飞走了, 想知道这种状态你必须经历以下几步:
因此这个status属性的值是一系列动作后才得到的结果,所以你每次调用时,其实它都要经过一系列的动作才返回你结果,但这些动作过程不需要用户关心, 用户只需要调用这个属性就可以.
1class Foo:
2 """ 描述类信息 """
3 def func(self):
4 pass
5
6print Foo.__doc__
__module__ 表示当前操作的对象在那个模块 __class__ 表示当前操作的对象的类是什么 aa.py
1class C:
2
3 def __init__(self):
4 self.name = 'fgf'
index.py
1from aa import C
2
3obj = C()
4print obj.__module__ # 输出 aa,即:输出模块
5print obj.__class__ # 输出 aa.C,即:输出类
通过类创建对象时,自动触发执行。
当对象在内存中被释放时,自动触发执行。
对象后面加括号,触发执行。 注:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 call 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()
1class Foo:
2 def __init__(self):
3 pass
4
5 def __call__(self, *args, **kwargs):
6 print ('__call__',args,kwargs)
7
8obj = Foo() # 执行 __init__
9obj(1,2,3,a=4,b=5) # 执行 __call__
查看类或对象中的所有成员
1class Province:
2 country = 'China'
3 def __init__(self, name, count):
4 self.name = name
5 self.count = count
6 def func(self, *args, **kwargs):
7 print ('func')
8
9# 获取类的成员,即:静态字段、方法、
10print (Province.__dict__)
11# 输出:{'country': 'China', '__module__': '__main__', 'func': <function func at 0x10be30f50>, '__init__': <function __init__ at 0x10be30ed8>, '__doc__': None}
12
13obj1 = Province('HeBei',10000)
14# 获取 对象obj1 的成员
15print (obj1.__dict__)
16# 输出:{'count': 10000, 'name': 'HeBei'}
如果一个类中定义了str方法,那么在打印对象 时,默认输出该方法的返回值。
1class Foo:
2 def __str__(self):
3 return 'fgf'
4
5obj = Foo()
6print (obj)
定以后,输入定义的值,不定义默认返回对象地址“<main.Foo object at 0x0000027BF421E9E8>”
用于索引操作,如字典。以上分别表示获取、设置、删除数据
1class Foo(object):
2 def __init__(self):
3 self.data = {}
4 def __getitem__(self, key):
5 print('__getitem__',key)
6 return self.data.get(key)
7 def __setitem__(self, key, value):
8 print('__setitem__',key,value)
9 self.data[key] = value
10 def __delitem__(self, key):
11 print('__delitem__',key)
12
13obj = Foo()
14
15obj['name'] = 'fgf' # 设置,自动触发执行 __setitem__
16print(obj.data)
17print(obj['name']) # 获取值,自动触发执行 __getitem__
18del obj['name'] # 触发__delitem__,只是调用那个方法,具体删不删看自己配置
1class Foo(object):
2 def __init__(self,name):
3 self.name = name
4f = Foo("fgf")
上述代码中,f 是通过 Foo类实例化的对象,其实,不仅f是一个对象,Foo类本身也是一个对象,因为在Python中一切事物都是对象。 如果按照一切事物都是对象的理论:obj对象是通过执行Foo类的构造方法创建,那么Foo类对象应该也是通过执行某个类的 构造方法 创建。
1print type(f) # 输出:<class '__main__.Foo'> 表示,obj 对象由Foo类创建
2print type(Foo) # 输出:<type 'type'> 表示,Foo类对象由 type 类创建
所以,f对象是Foo类的一个实例,Foo类对象是 type 类的一个实例,即:Foo类对象 是通过type类的构造方法创建。 那么,创建类就可以有两种方式:
1class Foo(object):
2
3 def func(self):
4 print 'hello fgf'
1def func(self):
2 print('hello fgf')
3
4Foo = type('Foo',(object,), {'talk': func})
5# type第一个参数:类名
6# type第二个参数:当前类的基类
7# type第三个参数:类的成员
8f = Foo()
9f.talk()
f是Foo的对象,Foo又是type的对象,所以type又称类的类 加上构造函数
1def func(self):
2 print("hello %s %s"%(self.name,self.age))
3
4def __init__(self,name,age):
5 self.name = name
6 self.age = age
7Foo = type('Foo',(object,),{'func':func,
8 '__init__':__init__})
9
10f = Foo("fgf",22)
11f.func()
So ,记住,类 是由 type类实例化产生,那么问题来了,类默认是由type类实例化产生,type类中如何实现的创建类?类又是如何创建对象? 答:类中有一个属性 __metaclass__,其用来表示该类由 谁来实例化创建,所以,我们可以为 __metaclass__ 设置一个type类的派生类,从而查看类创建的过程。 以下代码python2里运行看效果
1class MyType(type):
2 def __init__(self, what, bases=None, dict=None):
3 print("--MyType init---")
4 super(MyType, self).__init__(what, bases, dict)
5 def __call__(self, *args, **kwargs):
6 print("--MyType call---")
7 obj = self.__new__(self, *args, **kwargs)
8 self.__init__(obj, *args, **kwargs)
9
10class Foo(object):
11 __metaclass__ = MyType
12 def __init__(self, name):
13 self.name = name
14 print("Foo ---init__")
15 def __new__(cls, *args, **kwargs):
16 # __new__是用来创建实例的,定制类,先运行new里调用init,这里写,对默认的重构
17 print("Foo --new--")
18 # print(object.__new__(cls))
19 return object.__new__(cls) # 返回给init,cls这代表Foo,相当于对象的self
20 # 调用父类的__new__方法
21
22# 第一阶段:解释器从上到下执行代码创建Foo类
23# 第二阶段:通过Foo类创建obj对象
24obj = Foo("Fgf")
(默认之前应该还有个myType.new)先执行myType.init,再执行myType.call,再执行Foo.new,最后Foo.init
如果用户输入信息如”fgf”,通过输入字符串”fgf”去调用实例的属性,怎么实现。 不可能”name=input()”,再用name去调用fgf属性,那样调用的是name而不是fgf。 要想把用户输入字符串转为一个变量名,而不是一个值就需要用到: 反射(实现用户输入字符串为类的方法) 通过字符串映射或修改程序运行时的状态、属性、方法, 有以下4个方法 attr –> attribute [əˈtrɪbjut] 属性; (人或物的) 特征
判断object中有没有一个name字符串对应的方法或属性
1class Foo(object):
2 # name = ''
3 def __int__(self):
4 self.name = 'fgf'
5 def func(self):
6 return "func"
7
8obj = Foo()
9
10print(hasattr(obj, 'name')) # 输出False
11print(hasattr(obj, 'func')) # 输出True
根据字符串去获取obj对应方法的内存地址
1def getattr(object, name, default=None):
2 """
3 getattr(object, name[, default]) -> value
4 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
5 """
1class Foo(object):
2 def __init__(self):
3 self.name = 'fgf'
4 def func(self):
5 print(self.name,'say Hi')
6 return "func"
7
8obj = Foo()
9print(getattr(obj,'func'))
10getattr(obj, 'func')() # # same as: obj.func()
动态把一个函数装到类里面
1def setattr(x, y, v): # real signature unknown; restored from __doc__
2 """
3 setattr(x, 'y', v) is equivalent to ``x.y = v''
4 """
1def func1(self):
2 print(self.name,'say Hi')
3 return "func"
4
5class Foo(object):
6 def __init__(self):
7 self.name = 'fgf'
8 def func2(self):
9 print(self.name,'say fu')
10 return "func"
11obj = Foo()
12
13choice = input("请输入调用方法名[func1|func2]:")
14if hasattr(obj,choice): # 实例中有这个方法,执行实例中的方法
15 print(getattr(obj,choice))
16else: # 动态加载函数封装到类中
17 setattr(obj,choice,func1)
18 func = getattr(obj,choice)
19 func(obj)
删除set添加的属性
1def delattr(x, y): # real signature unknown; restored from __doc__
2 """
3 delattr(x, 'y') is equivalent to ``del x.y''
4 """
1class Foo(object):
2 def __init__(self):
3 self.name = 'fgf'
4 def func(self):
5 print(self.name,'say Hi')
6
7obj = Foo()
8
9setattr(obj, 'age', 18)
10print(obj.name,obj.age)
11# delattr(obj, 'func')
12delattr(obj,'age') # 只能删除setattr动态添加的,默认的不可以删除
13print(obj.name,obj.age)
动态导入模块
1import importlib
2
3__import__('import_lib.metaclass') #这是解释器自己内部用的
4#importlib.import_module('import_lib.metaclass') #与上面这句效果一样,官方建议用这个
isinstance(obj, cls):检查是否obj是否是类 cls 的对象 issubclass(sub, super):检查sub类是否是 super 类的派生类
在编程过程中为了增加友好性,在程序出现bug时一般不会将错误信息显示给用户,而是现实一个提示的页面
1try:
2 diction = {}
3 diction[1]
4 names = []
5 names[2]
6except IndexError as e: # python3.x 里不是逗号,都是as
7 print(e)
8except (KeyError,IndexError) as e: # 采用统一处理办法
9 print(e)
10except Exception as e: # 抓住所有错误
11 print(e)
12else: # 没出错执行这个
13 pass
14finally: # 不管有没有错,都执行
15 pass
16
17try:
18 status = 1
19 if status != 0 :
20 raise Exception("自定义异常")
21except Exception as e:
22 print(e)
声明:本文系网络转载,版权归原作者所有。如涉及版权,请联系删除!