python(七)上:面向对象进阶

目录

面向对象高级语法部分
  静态方法、类方法、属性方法
  类的特殊方法
  反射
异常处理

一、类的高级方法

1、静态方法(@staticmethod)

通过@staticmethod装饰器即可把其装饰的方法变为一个静态方法。普通的方法,可以在实例化后直接调用,并且在方法里可以通过self.调用实例变量或类变量,但静态方法是不可以访问实例变量或类变量的,一个不能访问实例变量和类变量的方法,其实相当于跟类本身已经没什么关系了,它与类唯一的关联就是需要通过类名来调用这个方法

class Dog(object):
    def __init__(self,name):
        self.name = name
    @staticmethod  # 把eat方法变为静态方法
    def eat(self):
        print("%s is eating" %self.name)

d = Dog("wangcai")
d.eat()

上面的调用会出以下错误,

TypeError: eat() missing 1 required positional argument: 'self'

说是eat需要一个self参数,但调用时却没有传递,没错,当eat变成静态方法后,再通过实例调用时就不会自动把实例本身当作一个参数传给self了。
想让上面的代码可以正常工作有两种办法

  1. 调用时主动传递实例本身给eat方法,即d.eat(d)
  2. 在eat方法中去掉self参数,但这也意味着,在eat中不能通过self.调用实例中的其它变量了
class Dog(object):
    def __init__(self,name):
        self.name = name
    @staticmethod  # 把eat方法变为静态方法
    def eat(self):
        print("%s is eating" %self.name)

d = Dog("wangcai")
d.eat(d)

作用:只是相当于一个单纯函数,要传参数,就要把实例传进去。
如果说和类有关系,就是必须有类名去调用。调用不了类或实例中的任何属性

2、类方法(@classmethod)

类方法通过@classmethod装饰器实现,类方法和普通方法的区别是:
类方法只能访问类变量,不能访问实例变量

class Dog(object):
    def __init__(self,name):
        self.name = name
    @classmethod
    def eat(self):
        print("%s is eating" % self.name)

d = Dog("wangcai")
d.eat()

执行报错如下,说Dog没有name属性,因为name是个实例变量,类方法是不能访问实例变量的

AttributeError: type object 'Dog' has no attribute 'name'

此时可以定义一个类变量,也叫name,看下执行效果

class Dog(object):
    name = "哮天犬"
    def __init__(self,name):
        self.name = name
    @classmethod
    def eat(self):
        print("%s is eating" % self.name)

d = Dog("wangcai")
d.eat()

3、属性方法(@property)(类似不动产)

属性方法的作用就是通过@property把一个方法变成一个静态属性
(函数–>变量)

class Dog(object):
    def __init__(self,name):
        self.name = name
    @property
    def eat(self):
        print("%s is eating" % self.name)

d = Dog("wangcai")
d.eat()

调用会出以下错误, 说NoneType is not callable, 因为eat此时已经变成一个静态属性了, 不是方法了, 想调用已经不需要加()号了,直接d.eat就可以了

TypeError: 'NoneType' object is not callable

正常调用如下:

d.eat
# 输出
wangcai is eating

但是有个问题,如果eat有其他参数,没法传参数。而且即使变成了静态属性,也没法像普通变量那样“=”赋值
怎么传参数呢?

  • 属性方法赋值
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

d = Dog("wangcai")
d.eat
d.eat = "baozi"
d.eat

如果传多个参数,‘d.eat = “baozi1”,”baozi2”’,接收为元组形式。

  • 如何删除属性方法呢

执行del删除

del d.eat

报错:

AttributeError: can't delete attribute

默认不能删除,要删除也是在类里再写一个方法

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("Delete the finished")

d = Dog("wangcai")
d.eat
d.eat = "baozi"
d.eat  # 传完参数后调用
del d.eat
d.eat  # 删完后调用

报错如下,说明已经删除了

AttributeError: 'Dog' object has no attribute '_Dog__food'

好吧,把一个方法变成静态属性有什么卵用呢?既然想要静态变量,那直接定义成一个静态变量不就得了么?well, 以后你会需到很多场景是不能简单通过 定义 静态属性来实现的, 比如 ,你想知道一个航班当前的状态,是到达了、延迟了、取消了、还是已经飞走了, 想知道这种状态你必须经历以下几步:

  1. 连接航空公司API查询
  2. 对查询结果进行解析
  3. 返回结果给你的用户

因此这个status属性的值是一系列动作后才得到的结果,所以你每次调用时,其实它都要经过一系列的动作才返回你结果,但这些动作过程不需要用户关心, 用户只需要调用这个属性就可以

二、类的特殊成员方法

1.__doc__  表示类的描述信息

class Foo:
    """ 描述类信息 """
    def func(self):
        pass

print Foo.__doc__

2.__module__ 和 __class__

__module__ 表示当前操作的对象在那个模块
__class__ 表示当前操作的对象的类是什么
aa.py

class C:

    def __init__(self):
        self.name = 'fgf'

index.py

from aa import C

obj = C()
print obj.__module__   # 输出 aa,即:输出模块
print obj.__class__    # 输出 aa.C,即:输出类

3.__init__ 构造方法,通过类创建对象时,自动触发执行。

4.__del__ 析构方法,当对象在内存中被释放时,自动触发执行。

5.__call__ 对象后面加括号,触发执行。

注:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 call 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()

class Foo:
    def __init__(self):
        pass

    def __call__(self, *args, **kwargs):
        print ('__call__',args,kwargs)

obj = Foo()         # 执行 __init__
obj(1,2,3,a=4,b=5)  # 执行 __call__

6.__dict__ 查看类或对象中的所有成员

class Province:
    country = 'China'
    def __init__(self, name, count):
        self.name = name
        self.count = count
    def func(self, *args, **kwargs):
        print ('func')

# 获取类的成员,即:静态字段、方法、
print (Province.__dict__)
# 输出:{'country': 'China', '__module__': '__main__', 'func': <function func at 0x10be30f50>, '__init__': <function __init__ at 0x10be30ed8>, '__doc__': None}

obj1 = Province('HeBei',10000)
# 获取 对象obj1 的成员
print (obj1.__dict__)
# 输出:{'count': 10000, 'name': 'HeBei'}

7.__str__ 如果一个类中定义了_str_方法,那么在打印 对象 时,默认输出该方法的返回值。

class Foo:
    def __str__(self):
        return 'fgf'

obj = Foo()
print (obj)

定以后,输入定义的值,不定义默认返回对象地址“<__main__.Foo object at 0x0000027BF421E9E8>”

8.__getitem__、__setitem__、__delitem__

用于索引操作,如字典。以上分别表示获取、设置、删除数据

class Foo(object):
    def __init__(self):
        self.data = {}
    def __getitem__(self, key):
        print('__getitem__',key)
        return self.data.get(key)
    def __setitem__(self, key, value):
        print('__setitem__',key,value)
        self.data[key] = value
    def __delitem__(self, key):
        print('__delitem__',key)

obj = Foo()

obj['name'] = 'fgf'   # 设置,自动触发执行 __setitem__
print(obj.data)
print(obj['name'])     # 获取值,自动触发执行 __getitem__
del obj['name']        # 触发__delitem__,只是调用那个方法,具体删不删看自己配置

9.类的起源 __new__和 __metaclass__

class Foo(object):
    def __init__(self,name):
        self.name = name
f = Foo("fgf")

上述代码中,f 是通过 Foo 类实例化的对象,其实,不仅 f 是一个对象,Foo类本身也是一个对象,因为在Python中一切事物都是对象。
如果按照一切事物都是对象的理论:obj对象是通过执行Foo类的构造方法创建,那么Foo类对象应该也是通过执行某个类的 构造方法 创建。

print type(f) # 输出:<class '__main__.Foo'>     表示,obj 对象由Foo类创建
print type(Foo) # 输出:<type 'type'>              表示,Foo类对象由 type 类创建

所以,f对象是Foo类的一个实例,Foo类对象是 type 类的一个实例,即:Foo类对象 是通过type类的构造方法创建。
那么,创建类就可以有两种方式:
a). 普通方式(也是通过type创建的类,只是已经封装好了)

class Foo(object):

    def func(self):
        print 'hello fgf'

b). 特殊方式

def func(self):
    print('hello fgf')

Foo = type('Foo',(object,), {'talk': func})
# type第一个参数:类名
# type第二个参数:当前类的基类
# type第三个参数:类的成员
f = Foo()
f.talk()

f是Foo的对象,Foo又是type的对象,所以type又称类的类
加上构造函数

def func(self):
    print("hello %s %s"%(self.name,self.age))

def __init__(self,name,age):
    self.name = name
    self.age = age
Foo = type('Foo',(object,),{'func':func,
                            '__init__':__init__})

f = Foo("fgf",22)
f.func()

So ,记住,类 是由 type 类实例化产生
那么问题来了,类默认是由 type类实例化产生,type类中如何实现的创建类?类又是如何创建对象?
答:类中有一个属性 __metaclass__,其用来表示该类由 谁 来实例化创建,所以,我们可以为 __metaclass__ 设置一个type类的派生类,从而查看 类 创建的过程。
以下代码python2里运行看效果

class MyType(type):
    def __init__(self, what, bases=None, dict=None):
        print("--MyType init---")
        super(MyType, self).__init__(what, bases, dict)
    def __call__(self, *args, **kwargs):
        print("--MyType call---")
        obj = self.__new__(self, *args, **kwargs)
        self.__init__(obj, *args, **kwargs)

class Foo(object):
    __metaclass__ = MyType
    def __init__(self, name):
        self.name = name
        print("Foo ---init__")
    def __new__(cls, *args, **kwargs):
        # __new__是用来创建实例的,定制类,先运行new里调用init,这里写,对默认的重构
        print("Foo --new--")
        # print(object.__new__(cls))
        return object.__new__(cls)  # 返回给init,cls这代表Foo,相当于对象的self
        # 调用父类的__new__方法

# 第一阶段:解释器从上到下执行代码创建Foo类
# 第二阶段:通过Foo类创建obj对象
obj = Foo("Fgf")

(默认之前应该还有个myType.new)先执行myType.init,再执行myType.call,再执行Foo.new,最后Foo.init
这里写图片描述


转载请务必保留此出处:http://blog.csdn.net/fgf00/article/details/52479307

三、反射

如果用户输入信息如”fgf”,通过输入字符串”fgf”去调用实例的属性,怎么实现。
不可能”name=input()”,再用name去调用fgf属性,那样调用的是name而不是fgf。
要想把用户输入字符串转为一个变量名,而不是一个值就需要用到:
反射(实现用户输入字符串为类的方法)
通过字符串映射或修改程序运行时的状态、属性、方法, 有以下4个方法
attr –> attribute [əˈtrɪbjut] 属性; (人或物的) 特征

  • hasattr(obj,name_str) :判断object中有没有一个name字符串对应的方法或属性
class Foo(object):
    # name = ''
    def __int__(self):
        self.name = 'fgf'
    def func(self):
        return "func"

obj = Foo()

print(hasattr(obj, 'name'))  # 输出False
print(hasattr(obj, 'func'))  # 输出True
  • getattr(obj,name_str):根据字符串去获取obj对应方法的内存地址
def getattr(object, name, default=None):
    """
    getattr(object, name[, default]) -> value
    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    """
class Foo(object):
    def __init__(self):
        self.name = 'fgf'
    def func(self):
        print(self.name,'say Hi')
        return "func"

obj = Foo()
print(getattr(obj,'func'))
getattr(obj, 'func')()  # # same as: obj.func()
  • setattr(obj,name_str,func)动态把一个函数装到类里面
def setattr(x, y, v): # real signature unknown; restored from __doc__
    """
    setattr(x, 'y', v) is equivalent to ``x.y = v''
    """
def func1(self):
    print(self.name,'say Hi')
    return "func"

class Foo(object):
    def __init__(self):
        self.name = 'fgf'
    def func2(self):
        print(self.name,'say fu')
        return "func"
obj = Foo()

choice = input("请输入调用方法名[func1|func2]:")
if hasattr(obj,choice):  # 实例中有这个方法,执行实例中的方法
    print(getattr(obj,choice))
else:                    # 动态加载函数封装到类中
    setattr(obj,choice,func1)
    func = getattr(obj,choice)
    func(obj)
  • delattr ()删除set添加的属性
def delattr(x, y): # real signature unknown; restored from __doc__
    """
    delattr(x, 'y') is equivalent to ``del x.y''
    """
class Foo(object):
    def __init__(self):
        self.name = 'fgf'
    def func(self):
        print(self.name,'say Hi')

obj = Foo()

setattr(obj, 'age', 18)
print(obj.name,obj.age)
# delattr(obj, 'func')
delattr(obj,'age')  # 只能删除setattr动态添加的,默认的不可以删除
print(obj.name,obj.age)

动态导入模块

import importlib

__import__('import_lib.metaclass') #这是解释器自己内部用的
#importlib.import_module('import_lib.metaclass') #与上面这句效果一样,官方建议用这个

isinstance(obj, cls):检查是否obj是否是类 cls 的对象
issubclass(sub, super):检查sub类是否是 super 类的派生类

四、异常处理

在编程过程中为了增加友好性,在程序出现bug时一般不会将错误信息显示给用户,而是现实一个提示的页面

try:
    diction = {}
    diction[1]
    names = []
    names[2]
except IndexError as e:             # python3.x 里不是逗号,都是as
    print(e)
except (KeyError,IndexError) as e:  # 采用统一处理办法
    print(e)
except Exception as e:              # 抓住所有错误
    print(e)
else:                               # 没出错执行这个
    pass
finally:                            # 不管有没有错,都执行
    pass

try:
    status = 1
    if status != 0 :
        raise Exception("自定义异常")
except Exception as e:
    print(e)

转载请务必保留此出处:http://blog.csdn.net/fgf00/article/details/52479307

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值