温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python描述器的用法

发布时间:2021-04-27 14:48:21 来源:亿速云 阅读:151 作者:小新 栏目:编程语言

这篇文章主要介绍python描述器的用法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

python有哪些常用库

python常用的库:1.requesuts;2.scrapy;3.pillow;4.twisted;5.numpy;6.matplotlib;7.pygama;8.ipyhton等。

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

1、说明

描述器必须是类属性,Python中,一个类实现了__get__ 、__set__、__delete__三个任意一个方法都称为描述器;

如果一个类的类属性设置为描述器,那么它被称为此描述器的owner。

2、实例方法的实现

Python的方法,普通的实例方法,包括staticmethod和classmethod,都实现为非数据描述器。因此,实例可以重新定义和覆盖方法,表现为正常的字典属性的访问和修改 。这允许单个实例获取与同一类的其他实例不同的行为。

3、实例

Python的方法,普通的实例方法,包括staticmethod和classmethod,都实现为非数据描述器。

class A:
    @classmethod  # 非数据描述器
    def foo(cls):
        pass
 
    @staticmethod  # 非数据描述器
    def bar():
        pass
 
    @property  # 数据描述器
    def z(self):
        return 5
 
    def getfoo(self): # 非数据描述器
        return self.foo
 
    def __init__(self): # 非数据描述器
        self.foo = 100
        self.bar = 200
        #self.z = 300 # AttributeError: can't set attribute  无法覆盖数据描述器的定义
 
 
a = A()
print(a.__dict__)  # {'foo': 100, 'bar': 200} 看不到z属性
print(A.__dict__) # {'__module__': '__main__', 'foo': <classmethod object at 0x0000017674C6B7B8>, 'bar': <staticmethod object at 0x0000017674C6B7F0>, 'z': <property object at 0x0000017674BCD598>, 'getfoo': <function A.getfoo at 0x0000017674C58C80>, '__init__': <function A.__init__ at 0x0000017674C58D08>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}

以上是“python描述器的用法”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI