Python高级笔记(七)魔法属性

1. 私有属性 名字重整

print(Test.__dict__)

{'__weakref__': <attribute '__weakref__' of 'Test' objects>, '__init__': <function Test.__init__ at 0x00000000010C59D8>, '__doc__': None, '__dict__': <attribute '__dict__' of 'Test' objects>, '__module__': '__main__'}

2. 魔法属性

2.1 __doc__

  • 表示类的描述信息

2.2 __module__和 __class__

  • __module__: 表示当前操作的对象在哪个模块

  • __class__: 表示当前操作的对象的类是什么

 

2.3 __init__

  • 初始化方法,通过类创建对象时,自动触发执行

2.4 __del__

  • 当对象在内存中被释放时,自动触发执行

  • 注:此方法一般无需定义,因为Python是高级语言,程序员无需关系内存的分配和释放,因此工作都是交给Python解释器来执行,所以,__del__的调用是 由解释器在进行垃圾回收时自动触发执行的。

2.5 __call__

  • 对象后面加括号,触发执行

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

# -*- encoding=utf-8 -*-

class Foo(object):
    def __init__(self):
        pass

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

c = Foo()
c()
Foo()()

2.6 __dict__

  • 类或对象中的所有属性

类的实例属性属于对象; 类中的类属性和方法等属于类

# -*- encoding=utf-8 -*-

class Foo(object):
    country = "douzi"

    def __init__(self, name, count):
        self.name = name
        self.count = count

    def func(self, *args, **kwargs):
        print("func")

# 获取类的属性,即:类属性,方法
print(Foo.__dict__)

# 获取对象obj1的属性
obj1 = Foo("test", 134)
print(obj1.__dict__)
{'__dict__': <attribute '__dict__' of 'Foo' objects>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None, 'func': <function Foo.func at 0x000000000A538378>, 'country': 'douzi', '__init__': <function Foo.__init__ at 0x00000000010E59D8>}
{'count': 134, 'name': 'test'}

2.7 __str__

  • 如果一个类中定一个 __str__方法,那么在打印对象时,默认输出该方法的返回值
class Foo(object):
    def __str__(self):
        return "douzi"

t = Foo()
print(t) 

douzi

2,8 __getitem__、__setitem__、__delitem__

  • 用于索引操作,如字典。以上分别表示获取、设置、删除数据
  • 表示实现了该三个方法,该类即当列表用
class Foo(object):

    def __getitem__(self, item):
        print("__getitem__:", item)

    def __setitem__(self, key, value):
        print("__setitem__:", key, value)

    def __delitem__(self, key):
        print("__delitem__:", key)

obj = Foo()

res = obj["k1"]       # 自动触发执行 __getitem__
obj["k2"] = "douzi"   # 自动触发执行 __setitem__
del obj["k1"]         # 自动触发执行 __delitem__

2.9 __getslice__、__setslice__、__delslice__

  • 该三个方法用于分片操作,如:列表
class Foo(object):

    def __getslice__(self, i, j):
        print("__getslice__:", i, j)

    def __setslice__(self, i, j, sequence):
        print("__setslice__:", i, j, sequence)

    def __delslice__(self, i, j):
        print("__delslice__:", i, j)


obj = Foo()

obj[0:2]
obj[0:2] = [11, 22, 33, 44]
del obj[0:2]

 

猜你喜欢

转载自www.cnblogs.com/douzujun/p/10829218.html