脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python 特殊属性及方法详细解析

python 特殊属性及方法详细解析

2022-07-20 19:25不负韶华ღ Python

这篇文章主要介绍了python 特殊属性及方法详细解析,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下

概述

在python中,以单下划线开头的(_a)的代表不能直接访问的类属性,需通过类提供的接口进行访问,不能用“from xxx import *”而导入,“单下划线” 开始的成员变量叫做保护变量,意思是只有类对象和子类对象自己能访问到这些变量;以双下划线开头的(_ _a)代表类的私有成员,意思是只有类对象自己能访问,连子类对象也不能访问到这个数据;以双下划线开头和结尾的(_ _a_ _)代表python里特殊方法专用的标识,如 _ _init_ _()代表类的构造函数。

特殊属性

1、 _ _ name _ _

如果是一个对象的调用,则表示类的名称,而不是表示对象的名称;如果当前模块被直接执行(主模块),_ _ name _ _ 存储的是_ _ main _ _ ;如果当前模块是被调用的模块(被导入),则_ _ name _ _存储的是py文件名(模块名称)。

1、表示对象的名称

?
1
2
3
4
5
6
7
8
9
10
11
12
>>> class A(object):
    a = 1
    def __init__(self):
        self.b = 'c'
>>> a = A()
>>> A.__name__
'A'
>>> a.__name__
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    a.__name__
AttributeError: 'A' object has no attribute '__name__'

2、表示_ _ main _ _函数的名称,也就是程序的入口,类似于java中main函数

python 特殊属性及方法详细解析

?
1
2
>>> __name__
'__main__'

3、如果当前模块被其他模块调用,则是当前模块的名称

demo1.py

?
1
print(__name__)

demo2.py

?
1
import demo1

运行demo2.py文件后,得到的结果为:

demo1

2、_ _ bases _ _ 和_ _ base _ _ 以及 _ _ mro _ _

_ _ bases _ _ 表示类的所有基类;_ _ base _ _ 输出类继承的第一个父类(类的基类); _ _ mro _ _ 输出类的层次结构。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
>>> class A:
    def __init__(self):
        self.a = 2
 
>>> class B(A):
    def __init__(self):
        super().__init__()
        self.b = 3
 
>>> class C(A):
    def __init__(self):
        super().__init__()
        self.c = 4
 
>>> class D(B, C):
    def __init__(self):
        super().__init__()
        self.d = 5
 
>>> D.__bases__
(<class '__main__.B'>, <class '__main__.C'>)
>>> D.__base__
<class '__main__.B'>
>>> D.__mro__
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)

3、_ _ class _ _

表示对象的类型,相当于type()函数。

?
1
2
3
4
5
6
7
>>> class A:
    def __init__(self):
        self.a = 2
 
>>> a = A()
>>> a.__class__
<class '__main__.A'>

4、_ _ dict _ _

表示对象和类的一些属性,用一个字典存储起来。

?
1
2
3
4
5
6
7
8
9
10
11
12
>>> class A:
    a = 1
    b = 2
    def __init__(self):
        self.c = 3
        self.d = 4
 
>>> a = A()
>>> a.__dict__
{'c': 3, 'd': 4}
>>> A.__dict__
mappingproxy({'__module__': '__main__', 'a': 1, 'b': 2, '__init__': <function A.__init__ at 0x000001CD66F6B8B0>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None})

特殊方法

1、 _ _ subclasses _ _ ()

表示类的所有直接子类。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
>>> class A:
        def __init__(self):
            self.a = 2
 
>>> class B(A):
        def __init__(self):
            super().__init__()
            self.b = 3
 
>>> class C(A):
        def __init__(self):
            super().__init__()
            self.c = 4
 
>>> class D(B, C):
        def __init__(self):
            super().__init__()
            self.d = 5
        
>>> C.__subclasses__()
[<class '__main__.D'>]
>>> A.__subclasses__()
[<class '__main__.B'>, <class '__main__.C'>]

2、_ _ new _ _ ()、 _ _ init _ _ ()和 _ _ del _ _ ()

_ _ new _ _ ()是一个静态方法,用于根据类型创建实例。Python在调用 _ _ new _ _ ()方法获得实例后,会调用这个实例的_ _ init _ _ ()方法,然后将最初传给 _ _ new _ _ ()方法的参数都传给 _ _ init _ _ ()方法。

_ _ init _ _ ()是一个实例方法,用来在实例创建完成后进行必要的初始化,该方法必须返回None。Python不会自动调用父类的 _ _ init _ _ ()方法,这需要额外的调用:

?
1
super(C, self). _ _ init _ _ ()

_ _ new _ _ ()至少要有一个参数cls,代表要实例化的类,此参数在实例化时由Python解释器自动提供;_ _ new _ _ ()必须要有返回值,返回实例化出来的实例,可以return父类new出来的实例,或直接是object的new出来的实例。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> class A(object):
        def __new__(cls, *args, **kwargs):
            print("__new__")
            instance = object.__new__(cls)
            # 或者
            # instance = super().__new__(cls)
            return instance
    
        def __init__(self):
            print("__init__")
 
>>> a = A()
__new__
__init__

在GC之前,Python会调用这个对象的 _ _ del _ _ ()方法完成一些终止化工作。如果没有 _ _ del _ _ ()方法,那么Python不做特殊的处理;此外,Python无视_ _ del _ _ ()方法的返回值;Python不会自动调用父类的 _ _ del _ _ ()方法,除非显式调用;定义了 _ _ del _ _ ()方法的实例无法参与到循环GC中,所以对于这样的实例应该避免循环引用;try/finally语句或with语句可能是比_ _ del _ _()更好的方式。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>>> class A(object):
        def __new__(cls, *args, **kwargs):
            print("__new__")
            instance = super().__new__(cls, *args, **kwargs)
            return instance
    
        def __init__(self):
            print("__init__")
    
        def __del__(self):
            print("__del__")
            
>>> a = A()
__new__
__init__
>>> del a
__del__

3、_ _ repr _ _ ()和 _ _ str _ _ ()

_ _ repr _ _ ()是一个 ”自我描述“ 的方法,也是Python类中的一个特殊方法,由object对象提供,由于object提供的这个 _ _ repr _ _ 方法总是返回一个对象, ( 类名 + obejct at + 内存地址 ),这个值并不能真正实现自我描述的功能,如果你想在自定义类中实现 “自我描述” 的功能,那么必须重写 _ _ repr _ _ 方法。_ _ repr _ _ ()方法返回的字符串主要是面向解释器的。

?
1
2
3
4
5
6
7
8
9
10
11
>>> class A(object):
        def __repr__(self):
            return "this is a class A"
 
>>> a = A()
>>> a
this is a class A
>>> print(a)
this is a class A
>>> str(a)
'this is a class A'

_ _ str _ _ ()与_ _ repr _ _ ()返回的详尽的、准确的、无歧义的对象描述字符串不同,_ _ str _ _ ()方法只是返回一个对应对象的简洁的字符串表达形式。如上代码所示,当_ _ str _ _ ()缺失时,Python会调用_ _ repr _ _ ()方法。

?
1
2
3
4
5
6
7
8
9
10
11
>>> class A(object):
        def __str__(self):
            return "this is a class A"
 
>>> a = A()
>>> a
<__main__.A object at 0x000001CF8C8F9640>
>>> print(a)
this is a class A
>>> str(a)
'this is a class A'

实际上_ _ str _ _ ()只是覆盖了_ _ repr _ _ ()以得到更友好的用户显示。Python内置的str()函数,print(x)语句,都会调用对象的_ _ str _ _()方法。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> class A(object):
    def __repr__(self):
        return "class A"
    
    def __str__(self):
        return "this is a class A"
 
>>> a = A()
>>> a
class A
>>> print(a)
this is a class A
>>> str(a)
'this is a class A'

4、_ _ call _ _ ()

定义了该方法的对象可以像函数那样被调用,因此被称为可调用对象。

?
1
2
3
4
5
6
7
8
9
10
>>> class A(object):
        def __init__(self):
            self.a = 2
    
        def __call__(self, b, *args, **kwargs):
            c = b + self.a
            return c
>>> a = A()
>>> a(3)
5

5、_ _ lt _ _ ()、_ _ le _ _ ()、_ _ gt _ _ ()、_ _ ge _ _ ()、_ _ eq _ _ ()、_ _ ne _ _ ()

当两个对象x、y分别进行x<y、x<=y、x>y、x>=y、x==y和x!=y运算时,会调用对应的函数。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
>>> class A(object):
        def __init__(self, b):
            self.b = b
    
        def __lt__(self, other):
            print("__lt__")
            return self.b < other.b
 
>>> c = A(3)
>>> d = A(4)
>>> c < d
__lt__
True

6、_ _ hash _ _ ()

三种情形会调用__hash__()方法:1. 内置的hash()方法,2.作为字典的键时,3.作为集合的成员时;_ _ hash _ _ ()方法应该返回一个32位长的整数,对与同一个对象,hash()方法应该总是返回相同的值;对于 x == y ,即使二者不属于相同的类型,只要他们是可哈希的(hashable),都应该确保得到 hash(x) == hash(y) ;

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
>>> class A(object):
        def __init__(self, n):
            self.n = n
    
        def __eq__(self, other):
            return self.n == other.n
    
        def __hash__(self):
            return random.randint(0, 10)
 
 
>>> a = A(3)
>>> b = A(3)
>>> a == b
True
# 虽然a == b返回结果为True,但是hash(a)和hash(b)返回结果不一样,所以不能说这两个对象是相同的。
>>> hash(a)
3
>>> hash(b)
5

_ _ eq _ _()正确的用法:

?
1
2
3
4
5
6
7
8
9
10
11
12
class A(object):
    def __init__(self, n):
        self.n = n
            
    def __hash__(self):
        return hash(id(self))
        
    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return hash(id(self))==hash(id(other))
        else:
            return False

通过_ _ hash _ _ 返回一个int值,用来标记这个对象。对于类而言,如果没有实现_ _ eq _ _ ()和 _ _ hash _ _ ()函数,那么会自动继承object._ _ hash _ _()。

到此这篇关于python 特殊属性及方法详细解析的文章就介绍到这了,更多相关python 属性方法内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_49346755/article/details/125869189

延伸 · 阅读

精彩推荐