Python3 面向对象进阶

本文介绍了Python3中面向对象的高级特性,包括反射的概念及其在Python中的应用,如通过字符串操作对象属性。同时,详细探讨了双下划线方法(如_len_、_hash_、_str_、_repr_、_call_等),阐述了它们在类和对象中的特殊意义,并提到了自定义上下文管理器的重要性。
摘要由CSDN通过智能技术生成

一、反射

1 什么是反射

反射的概念是由Smith在1982年首次提出的,主要是指程序可以访问、检测和修改它本身状态或行为的一种能力(自省)。这一概念的提出很快引发了计算机科学领域关于应用反射性的研究。它首先被程序语言的设计领域所采用,并在Lisp和面向对象方面取得了成绩。

2 python面向对象中的反射:通过字符串的形式操作对象相关的属性。python中的一切事物都是对象(都可以使用反射)

四个可以实现自省的函数,下列方法适用于类和对象(一切皆对象,类本身也是一个对象)

# hasattr
def hasattr(*args, **kwargs): # real signature unknown
    """
    Return whether the object has an attribute with the given name.   
    This is done by calling getattr(obj, name) and catching AttributeError.
    """
    pass

# getattr
def getattr(object, name, default=None): # known special case of getattr
    """
    getattr(object, name[, default]) -> value
    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.
    """
    pass

def setattr(x, y, v): # real signature unknown; restored from __doc__
    """
    Sets the named attribute on the given object to the specified value.
    setattr(x, 'y', v) is equivalent to ``x.y = v''
    """
    pass

def delattr(x, y): # real signature unknown; restored from __doc__
    """
    Deletes the named attribute from the given object.
    delattr(x, 'y') is equivalent to ``del x.y''
    """
    pass

# 四个方法的使用演示
class Foo:
    f='类的静态变量'
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def say_hi(self):
        print('hi,%s' %self.name)
obj=Foo('egon',73)
#检测是否含有某属性
print(hasattr(obj,'name')) # True
print(hasattr(obj,'say_hi')) # True

#获取属性
n=getattr(obj,'name')
print(n) # egon
func=getattr(obj,'say_hi')
func() # hi,egon
# print(getattr(obj,'aaaaa')) #报错

#设置属性
setattr(obj,'sb',True)
setattr(obj,'show_name',lambda self:self.name+'sb')
print(obj.__dict__) # {'name': 'egon', 'age': 73, 'sb': True, 'show_name': <function <lambda> at 0x0000025179332EA0>}
print(obj.show_name(obj)) # egonsb

#删除属性
delattr(obj,'age')
delattr(obj,'show_name')
# delattr(obj,'show_name888') # 不存在,报错
print(obj.__dict__) #{'name': 'egon', 'sb': True}

类也是对象

class Foo(object):
    staticField='old boy'
    def __init__(self):
        self.name='wupeiqi'
    def func(self):
        return 'func'
    @staticmethod
    def bar():
        return 'bar'
print(getattr(Foo,'staticField')) 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值