Python-- 魔术方法

Python 魔术方法 详解 Python 魔术方法1、特殊属性2、查看属性2.1 示例 13、魔术方法3.1 实例化 `__new__`3.2 可视化3.3 `hash`3.4 `__bool__`3.5 运算符重载3.5.1 运算符重载应用场景 13.5.2 运算符重载应用场景 23.6 容器相关魔术方法3.7 可调用对象 1、特殊属性 2、查看属性 __dir__ 返回类或者对象的所有成员名称列表 dir()函数操作实例就是调用__dir__() 如果dir([obj])参数obj包含方法__dir__(),该方法 阅读详情

特殊属性

在这里插入图片描述

查看属性

  • 方法:
    __dir__
  • 意义:
    返回类或者对象的所有成员名称列表
    dir()函数操作实例就是调用__dir__()

如果dir([obj])参数obj包含方法__dir__(),该方法将被调用。如果参数obj不包含__dir__(),该方法将最大限度地收集属性信息

dir(obj)对于不同类型的对象obj具有不同的行为:

  • 如果对象是模块对象,返回的列表包含模块的属性名和变量名
  • 如果对象是类型或者说是类对象,返回的列表包含类的属性名,及它的祖先类的属性名
  • 如果是类的实例
    • 有 __dir__方法,返回可迭代对象的返回值
    • 没有__dir__方法,则尽可能收集实例的属性名、类的属性和祖先类的属性名
  • 如果obj不写,返回列表包含内容不同
    • 在模块中,返回模块的属性和变量名
    • 在函数中,返回本地作用域的变量名
    • 在方法中,返回本地作用域的变量名
# animal.py
class Animal:
    x = 123
    def __init__(self, name):
        self._name = name
        self.__age = 10
        self.weight = 20
print('animal Module\'s name = {}'.format(dir())) # 模块的属性

# cat.py
import animal
from animal import Animal

class Cat(Animal):
    x = 'cat'
    y = 'abcd'

class Dog(Animal):
    def __dir__(self):
        return ['dog'] # 必须返回可迭代对象

print('-------------')
print(1, 'Current Module\'s names = {}'.format(dir())) # 模块名词空间内的属性
print(2, 'animal Module\'s names  = {}'.format(dir(animal))) # 指定模块名词空间内的属性
print('=============')
print(3, "object's __dict__      = {}".format(sorted(object.__dict__.keys()))) # object的字典
print(4, "Animal's dir()         = {}".format(dir(Animal))) # 类Animal的dir()
print(5, "Cat's dir()            = {}".format(dir(Cat))) # 类Cat的dir()
print('~~~~~~~~~~~~~~')
tom = Cat('tom')
print(6, sorted(dir(tom))) # 实例tom的属性、Cat类及所有祖先类的属性
print(7, sorted(tom.__dir__())) # 同上
# dir()的等价近似如下,__dict__字典中几乎包括了所有属性
print(8, sorted(set(tom.__dict__.keys()) | set(Cat.__dict__.keys() | set(object.__dict__.keys()))))

print(9, "Dog'sdir = {}".format(dir(Dog)))
dog = Dog('snoppy')
print(10, dir(dog))
print(11, dog.__dict__)

执行# cat.py 结果如下/

animal Module's name = ['Animal', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
-------------

1 Current Module's names = ['Animal', 'Cat', 'Dog', '__annotations__', '__builtins__', '__cached__',\
 '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'animal']

2 animal Module's names  = ['Animal', '__builtins__', '__cached__',\
 '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']

=============
3 object's __dict__      = ['__class__', '__delattr__', '__dir__',\
 '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',\
  '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__',
   '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', \
   '__sizeof__', '__str__', '__subclasshook__']

4 Animal's dir()         = ['__class__', '__delattr__', '__dict__', \
'__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',\
 '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__',\
  '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',\
   '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'x']

5 Cat's dir()            = ['__class__', '__delattr__', '__dict__', '__dir__', \
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', \
'__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', \
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',\
 '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'x', 'y']
 
~~~~~~~~~~~~~~

6 ['_Animal__age', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__',\
 '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__',\
  '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__',\
   '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',\
    '__str__', '__subclasshook__', '__weakref__', '_name', 'weight', 'x', 'y']
    
7 ['_Animal__age', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', \
'__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', \
'__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__',\
 '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', \
 '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_name', 'weight', 'x', 'y']
 
8 ['_Animal__age', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__',\
 '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__',\
  '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__',\
   '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__'\
   , '__str__', '__subclasshook__', '_name', 'weight', 'x', 'y']
   
9 Dog's dir = ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', \
'__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__',\
 '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', \
 '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',\
 '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'x']
 
10 ['dog']

11 {'_name': 'snoppy', '_Animal__age': 10, 'weight': 20}
  • dir()的测试如下
class Person:
    def show(self):
        a = 100
        t = int(a)
        print(1, dir())
        print(2, locals())

def test(a=50, b=100):
    c = 150
    print(3, dir())
    print(4, locals())

Person().show()
test()

print(5, dir())
print(6, sorted(locals().keys()))
print(7, sorted(globals().keys()))

# 执行结果如下
1 ['a', 'self', 't']
2 {'t': 100, 'a': 100, 'self': <__main__.Person object at 0x00000178C74449B0>}
3 ['a', 'b', 'c']
4 {'c': 150, 'b': 100, 'a': 50}
5 ['Person', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'test']
6 ['Person', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'test']
7 ['Person', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'test']

内建函数

  • locals() 返回当前作用域中的变量字典
  • globals() 当前模块全局变量的字典

魔术方法

分类

  • 创建、初始化与销毁
    • __new__
    • __init__与__del__
  • 可视化
  • hash
  • bool
  • 运算符重载
  • 容器和大小
  • 可调用对象
  • 上下文管理
  • 反射
  • 描述器
  • 其他杂项

实例化

__new__

  • 实例化一个对象
  • 该方法需要返回一个值,如果该值不是cls的实例,则不会调用__init__
  • 该方法永远都是静态方法
class A:
    def __new__(cls, *args, **kwargs):
        print(cls)
        print(args)
        print(kwargs)
        # return super().__new__(cls)
        # return 1
        return None

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

a = A()
print(a)

# 执行结果
<class '__main__.A'>
()
{}
None

__new__方法很少使用,即使创建了该方法,也会使用return super().__new__(cls) 基类object的__new__方法来创建实例并返回

可视化

__str__

  • str()函数、format()函数、print()函数调用,需要返回对象的字符串表达。如果没有定义,就去调用__repr__方法返回字符串表达,如果__repr__没有定义,直接返回对象的内存地址信息

__repr__

  • 内建函数repr()对一个对象获取字符串表达
  • 调用__repr__方法返回字符串表达,如果__repr__也没有定义,就直接返回object的定义,就是显示内存地址信息

__bytes__

  • bytes()函数调用,返回一个对象的bytes表达,即返回bytes对象
class A:
    def __init__(self, name, age=19):
        self.name = name
        self.age = age

    def __repr__(self):
        return 'repr: {},{}'.format(self.name, self.age)

    def __str__(self):
        return 'str: {},{}'.format(self.name, self.age)

    def __bytes__(self):
        # return "{} is {}".format(self.name, self.age).encode()
        import json
        return json.dumps(self.__dict__).encode()

print(A('tom'))
print('{}'.format(A('tom')))
print([A('tom')])
print([str(A('tom'))])
print(bytes(A('tom')))

# 执行结果
str: tom,19
str: tom,19
[repr: tom,19]
['str: tom,19']
b'{"name": "tom", "age": 19}'

hash

__hash__

  • 内建函数hash()调用的返回值,返回一个整数,如果定义个方法该类的实例就可hash
print(hash(1))
print(hash(100000))
print(hash('tom'))
print(hash(('tom',)))

# 执行结果
1
100000
3667610206148835051
2658757694414170484
class A:
    def __init__(self, name, age=18):
        self.name = name

    def __hash__(self):
        return 1

    def __repr__(self):
        return self.name

print(hash(A('tom'))) # 1
print((A('tom'), A('tom'))) # (tom, tom)
print([A('tom'), A('tom')]) # [tom, tom]
print('~~~~~~~~~~~~~~~~~~')

a1 = A('tom')
a2 = A('tom')
s = {a1, a2}
print(s) # {tom, tom}
print(hash(a1), hash(a1)) # 1 1

t1 = ('tom',)
t2 = ('tom',)
print(t1 is t2) # False
print(t1 == t2) # True
print({t1,t2}, hash(t1), hash(t2)) # {('tom',)} 7607324171405129534 7607324171405129534
print({('tom',), ('tom',)}) # {('tom',)}
print({'tom', 'tom'}) # {'tom'}

上例中,A的实例放在set中,他们hash值是相同的,并没有去重

class A:
    def __init__(self, name, age=18):
        self.name = name

    def __hash__(self):
        return 1
    def __eq__(self, other):
        return self.name == other.name

    def __repr__(self):
        return self.name

print(hash(A('tom'))) # 1
print((A('tom'), A('tom'))) # (tom, tom)
print([A('tom'), A('tom')]) # [tom, tom]
s = {A('tom'), A('tom')}
print(s) # {tom}

__eq__

  • 对应==操作符,判断2个对象是否相等,返回bool值
  • 定义了这个方法,如果不提供__hash__方法,那么实例将不可hash

总结

  • 对整数取哈希采用的是取模算法
  • hash是看内容是否相同;set去重 ,哈希值相等且内容相同
  • __hash__方法只是返回一个hash值作为set的key,但是去重,还需要__eq__来判断2个对象是否相等
  • hash值相等,只是hash冲突,并不能说明两个对象是相等的
  • 因此,一般来说提供__hash__方法是为了作为set或者dict的key,如果去重要同时提供__eq__方法
  • 去重需要提供__eq__方法

list类实例为什么不可hash?

  • 源码中有一句__hash__ = None,也就是如果调用__hash__()相当于None(),一定报错
  • 所有类都继承object,而这个类是具有__hash__()方法的,如果一个类不能被hash,就把__hash__设置为None

functolls.lru_chche使用到的functools.HashedSwq类继承自list,为什么可hash?

  • _HashedSeq类提供了__hash__方法,这个方法实际上计算的是元组的hahs值

练习

设计二维坐标类Point,使其成为可hash类型,并比较2个坐标的实例是否相等

from collections import Hashable

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __hash__(self):
        return hash((self.x,self.y))

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

p1 = Point(4, 5)
p2 = Point(4, 5)
print(hash(p1)) # 3713084879518070856
print(hash(p2)) # 3713084879518070856

print(p1 is p2) # False
print(p1 == p2) # True
print(hex(id(p1)),hex(id(p2))) # 0x1b8e5bc8278 0x1b8e5bc8400
print(set((p1, p2))) # {<__main__.Point object at 0x000001B8E5BC8278>}

print(isinstance(p1, Hashable)) # True

bool

__bool__

内建函数bool(),或者对象放在逻辑表达式的位置,调用这个函数返回布尔值
没有定义__bool__(),就找__len__()返回长度,非0为真
如果__len__()没有定义,那么所有实例都返回真

class A:pass

print(bool(A())) # True

if A():
    print('Real A') # Real A

class B:
    def __bool__(self):
        return False

print(bool(B)) # True
print(bool(B())) # False
if B():
    print('Real B')

class C:
    def __len__(self):
        return 0

print(bool(C())) # False
if C():
    print('Real C')

运算符重载

operator模块提供以下的特殊方法,可以将类的实例使用下面的操作符来操作

运算符特殊方法含义
<,<=,==,>,>=,!=__lt__,__le__,__eq__, __gt__,__ge__,__ne__比较运算符
+, -, *, /, %, //, **, divmod__add__,__sub__,__mul__,__truediv__,__mod__,
__floordiv__,__pow__,__divmod__
算数运算符,
移位、位运算也有对应的方法
+=, -=,*=,/=,%=,//=,**=__iadd__,__isub__,__imul__, __itruediv__,__impd__,__ifloordiv__,__ipow__in-place
就地修改
  • 实现A类的2个实例相减
 class A:
    def __init__(self,name, age=18):
        self.name = name
        self.age = age

    def __sub__(self, other):
        return self.age - other.age

    def __isub__(self, other): # 如果没有定义__isub__,则会调用__sub__
        return A(self.name, self - other)

tom = A('tom')
jack = A('jack', 10)

print(tom - jack) # 8
print(jack - tom, jack.__sub__(tom)) # -8 -8

print(id(tom)) 2333399746152
tom -= jack
print(tom.age, id(tom))  # 8 2333399746320
  • __isub__ 方法定义,一般会in-place就地来修改自身
  • 如果没有定义__isub__方法,则会调用__sub__

练习

完成Point类设计,实现判断点相等的方法,并完成向量的加法
A(X1,Y1) B(X2,Y2) , 则A+B=(X1+X2, Y1+Y2), A-B= (X1-X2, Y1-Y2)

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

    def add(self,other):
        return (self.x + other.x, self.y + other.y)

    def __str__(self):
        return '<Point: {},{}>'.format(self.x, self.y)

p1 = Point(1,1)
p2 = Point(1,1)

print(p1.add(p2)) # (2, 2)
# 运算符重载
print(p1 + p2) # <Point: 2,2>

print(p1 == p2) # True

运算符重载应用场景

  • 往往是用面向对象实现的类,需要做大量的运算,而运算符是这种运算在数学上最常见的表达方式。例如,上例中的对+进行了运算符重载,实现了Point类的二元操作,重新定义为Point + Point
  • 提供运算符重载,比直接提供加法方法要更加合适该领域内使用者的习惯
  • int类,几乎实现了所有操作符,可以作为参考
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __eq__(self, other):
        return self.age == other.age

    def __gt__(self, other):
        return self.age > other.age

    def __ge__(self, other):
        return self.age >= other.age

tom = Person('tom', 20)
jack = Person('jack', 16)

print(tom > jack) # True
print(tom < jack) # False

print(tom >= jack) # True
print(tom <= jack) # False

print(tom == jack) # False
print(tom != jack) # True

__eq__等于可以推断不等于
__gt__大于可以推断小于
__ge__大于等于可以推断小于等于

容器相关方法

运算符意义
__len__内建函数len(),返回对象的长度(>=0的整数),如果把对象当做容器类型看,就如同list或者dict
bool()函数调用的时候,如果没有__bool()方法,则会看__len()__方法是否存在,存在返回非0为真
__iter__迭代容器时,调用,返回一个新的迭代器对象
__contains__in成员运算符,没有实现,就调用__iter__方法遍历
__getitem__实现self[key]访问。序列对象,key接受整数位索引,或者切片
对于set和dict,key为hashable。key不存在引发KeyError异常
__setitem__和__getitem__的访问类似,是设置值的方法
__missing__字典或其子类使用__getitem__()调用时,key不存在执行该方法
class A(dict):
    def __missing__(self, key):
        print('Missing key :', key)
        return 0

a = A()
print(a['k'])

# 执行结果
Missing key : k
0

练习

将购物车类改造成方便操作的容器类

class Cart:
    def __init__(self):
        self.items = []

    def __len__(self):
        return len(self.items)

    def additem(self, item):
        self.items.append(item)

    def __iter__(self):
        # yield from self.items
        return iter(self.items)

    def __getitem__(self, index): # 索引访问
        return self.items[index]

    def __setitem__(self, key, value): # 索引赋值
        self.items[key] = value

    def __str__(self):
        return str(self.items)

    def __add__(self, other):
        self.items.append(other)
        return self

cart = Cart()
cart.additem(1)
cart.additem('abc')
cart.additem(3)

# 长度、bool
print(len(cart)) # 3
print(bool(cart)) # True

# 迭代
for x in cart:
    print(x) # 1 abc 3

# in
print(3 in cart) True
print(2 in cart) False

# 索引操作
print(cart[1]) abc
cart[1] = 'xyz'
print(cart) # [1, 'xyz', 3]

# 链式编程实现加法
print(cart + 4 + 5 + 6) # [1, 'xyz', 3, 4, 5, 6]
print(cart.__add__(17).__add__(18)) # [1, 'xyz', 3, 4, 5, 6, 17, 18]

可调用对象

Python中一切皆对象,函数也不例外

def foo():
    print(foo.__module__, foo.__name__)

foo() # __main__ foo
# 等价于
foo.__call__() # __main__ foo
  • 函数即对象,对象foo加上(),就是调用此函数对象的__call__()方法

可调用对象

方法意义
__call__类中定义一个该方法,实例就可以像函数一样调用

可调用对象,定义一个类,并实例化得到其实例,将实例像函数一样调用

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __call__(self, *args, **kwargs):
        return "<Point {}:{}>".format(self.x, self.y)

p = Point(4, 5)
print(p)
print(p())

# 累加
class Adder:
    def __call__(self, *args):
        ret = 0
        for x in args:
            ret += x
        self.ret = ret
        return ret
    
adder = Adder()
print(adder(4, 5, 6))
print(adder.ret)

# 执行结果
<__main__.Point object at 0x000001B1A49F8630>
<Point 4:5>
15
15

练习

定义一个斐波那契数列的类,方便调用,计算第n项
增加迭代的方法、返回容器长度、支持索引的方法

class Fib:
    def __init__(self):
        self.items = [0, 1, 1]

    def __call__(self, index):
        if index < 0:
            raise IndexError('Wrong Index')
        if index < len(self.items):
            return self.items[index]

        for i in range(len(self.items), index+1):
            self.items.append(self.items[i-1] + self.items[i-2])
        return self.items[index]

print(Fib()(101)) # 573147844013817084101

在上例基础上,增加迭代的方法、返回容器长度、支持索引的方法

class Fib:
    def __init__(self):
        self.items = [0, 1, 1]

    def __call__(self, index):
        return self[index]

    def __iter__(self):
        return iter(self.items)

    def __len__(self):
        return len(self.items)

    def __getitem__(self, index):
        if index < 0:
            raise IndexError('Wrong Index')
        if index < len(self.items):
            return self.items[index]

        for i in range(len(self.items), index+1):
            self.items.append(self.items[i-1] + self.items[i-2])
        return self.items[index]

    def __str__(self):
        return str(self.items)

    __repr__ = __str__

fib = Fib()
print(fib(5), len(fib)) # 5 6

print(fib(10), len(fib)) # 55 11

for x in fib:
    print(x)
# 0
# 1
# 1
# 2
# 3
# 5
# 8
# 13
# 21
# 34
# 55

print(fib[5], fib[6]) # 5 8

可以看出使用类来实现斐波那契数列也是非常好的实现,还可以缓存数据,便于检索

python魔术方法 Python 类的“魔术方法”(Magic Methods)是一个非常核心且强大的特性。它们也被称为“特殊方法”或“Dunder Methods”(因为它们以双下划线 `__` 开头和结尾,Double Underscores)。 这些方法允许你自定义你的类,使其能够与 Python 的内置函数和操作符(如 `+`, `len()`, `print()`, `for` 循环等)无缝集成。通过实现这些方法,你可以让你的自定义对象表现得像 Python 的原生类型(如列表、字典、数字)一样。 阅读详情

相关推荐

Python常见的魔术方法和魔术属性

Python的魔术方法(也称为特殊方法)是对象的一些特殊方法,它们都是以双下划线开头。并以双下划线结尾,例如__init__。 魔术方法所体现的设计思想是构成python风格的重要组成部分。

景天科技苑 1716

python魔法方法有啥用-python的常用魔法方法详细总结

__init__我们很熟悉了,它在对象初始化的时候调用,我们一般将它理解为"构造函数".实际上, 当我们调用x = SomeClass()的时候调用,__init__并不是第一个执行的, __new__才是。所以准确来说,是__new__和__init__共同构成了"构造函数".__new__是用来创建类并返回这个类的实例, 而__init__只是将传入的参...

weixin_39621044的博客 353

Python常用魔术方法

什么是魔术方法?在Python中,所有以双下划线__包起来的方法,统称为Magic Method(魔术方法),它是一种的特殊方法,普通方法需要调用,而魔术方法不需要调用就可以自动执行。魔...

吾非同 2724

Python反序列化漏洞及魔术方法详细全解(链构造、自动审计工具bandit)

魔术方法执行调用下面的代码,如果下面的代码可控的话,就可能存在反序列化漏洞。pickle.dump(obj, file) :将对象序列化后保存到文件。 pickle.load(file) :读取文件, 将文件中的序列化内容反序列化为对象。 pickle.dumps(obj) :将对象序列化成字符串格式的字节流。 pickle.loads(bytes_obj) :将字符串格式的字节流反序列化为对象。寻找LV6 -> 购买修改支付逻辑 -> 绕过admin限制需修改jwt值 -> 爆破jwt密匙 -> 重组jw

ranzi. 4794

手把手教你用Logisim搭建5级流水MIPS CPU(附华中科技计组实验避坑指南)

本文详细介绍了如何使用Logisim从零构建5级流水MIPS CPU,特别针对华中科技大学计算机组成原理实验提供实用指南。内容涵盖单周期CPU过渡、流水线寄存器设计、数据冒险处理等核心环节,并附有实验避坑建议和性能优化技巧,帮助学生高效完成这一挑战性项目。

weixin_42532938的博客 371

避坑指南:ANSYS流固耦合计算中System Coupling数据传递设置与常见报错解决

本文深入解析ANSYS Workbench中System Coupling模块在双向流固耦合(FSI)计算中的应用,详细讲解数据传递机制、典型报错解决方案及高阶调试技巧。通过实际案例展示如何优化耦合步长、处理大变形问题,并提升并行计算效率,帮助工程师有效规避常见技术陷阱。

weixin_29213525的博客 724

python——魔术方法

特殊方法 1.__init__魔术方法 初始化魔术方法 2.__new__魔术方法 对象初始化: ​ 先执行 _ new _ :分配内存空间,并返回构建好的对象(的地址) ​ 再执行 _ init _:为构建好的对象赋予初始化 class Pig: #object是定义python所有库函数和底层逻辑的类 def __new__(cls,*arg,**kwargs): return object.__new__(cls) def __init

qq_53893431的博客 4584

【随机过程】Markov Chain的定义及发展历程与实际应用

本模块书写的初衷:由于在学习张波张景肖等学者所著的《应用随机过程》存在着不甚了解的知识点,经过个人查找资料并整理、分享,希望能够为有同样疑惑的读者贡献绵薄之力,同时如果个人编写内容有错误,恳请读者指正。本文为对《应用随机过程》第42页中Markov Chain基本概念的补充。1.Markov Chain的定义俄国数学家 Andrey Andreyevich Markov 研究并提出一个用数学方法就能解释自然变化的一般规律模型,被命名为马尔科夫链(Markov Chain)。

qq_49657150的博客 3743

介绍Python的魔术方法 - Magic Method

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_33806914的博客 305

MATLAB双目相机标定:从工具箱实战到参数精解

本文详细讲解了使用MATLAB进行双目相机标定的完整实战流程与参数精解。从拍摄合格的棋盘格图像、设置关键参数(如径向畸变系数),到分析重投影误差、优化结果并正确导出和使用内外参,提供了从操作到原理的全面指导,帮助读者为立体视觉应用奠定精准基础。

weixin_29041767的博客 257

Office 365中的Assigned Access详细功能介绍

本文系统介绍了Office365中AssignedAccess功能的应用与管理。作为Windows系统的重要安全特性,AssignedAccess可将设备锁定为单应用模式,有效防范未授权访问。文章详细阐述了其核心功能、技术架构及配置方法,包括UWP/Win32应用支持、多用户配置、与AzureAD集成等。通过MicrosoftEndpointManager可实现批量部署和远程监控,适用于公共终端、零售设备等场景。该功能为企业数字化转型提供了安全、可控的终端管理方案,在保障数据安全的同时优化用户体验。

xueyunshengling的博客 226

python __reduce__魔法方法_Python中的魔法方法整理

__init__我们很熟悉了,它在对象初始化的时候调用,我们一般将它理解为"构造函数".实际上, 当我们调用x = SomeClass()的时候调用,__init__并不是第一个执行的, __new__才是。所以准确来说,是__new__和__init__共同构成了"构造函数".__new__是用来创建类并返回这个类的实例, 而__init__只是将传入的参数来初始化该实例.__new__在创建一...

weixin_39809584的博客 875

后台管理系统-7-vue3之引入配置文件baseURL

mock=false,本地模拟。mock=true,线上模拟。baseURL+url=实际请求的URL。get请求param参数,post请求data参数。

qq_20466211的博客 207

Python魔术方法

所有以双下划线__包起来的方法,统称为,它是一种的特殊方法,普通方法需要调用,而魔术方法不需要调用就可以执行。魔术方法在类或对象的某些事件出发后会自动执行,让类具有神奇的“魔力”。如果希望根据自己的程序定制自己特殊功能的类,那么就需要对这些方法进行重写。

5952

围绕国产化操作系统以及人大金仓地理空间库的GIS的解决方案,含超详细部署步骤以及与QGIS,GeoServer,PostGlS Shapefile lmport/Export Manager的连接步骤

人大金仓软件 2.1软件的下载以及授权的相关文件插件 2.2上传至虚拟机 2.3KingbaseES V8R6数据库部署过程 2.3.1创建安装用户 2.3.2赋权 2.3.3.创建安装目录且赋权 2.3.4 准备挂载 2.4kingbase安装方法 2.7postgis安装 3 人大金仓数据库与QGIS的连接 4 人大金仓数据库与PostGlS Shapefile lmport/Export Manager的连接 5 人大金仓数据库与geoserver的连接

挣钱花388的博客 2590

从零开始讲DDR(8)——AXI 接口MIG 使用(1)

我们简单拆解了MIG AXI接口中测试文件的整体框架,首先在sim_tb_top.sv文件中例化了DDR模型和example_top。在example_top中,又例化了MIG IP和一个流量产生器ddr4_v2_2_8_axi_tg_top。在ddr4_v2_2_8_axi_tg_top中的主要功能是分别例化了boot_mode_gen,prbs_mode_gen,custom_mode_gen和axi_opcode_gen。

apple_53311083的博客 1587

Python中魔术方法汇总

Python魔术方法汇总,附代码实例说明

使者大牙ℂypher的博客 3333

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

Python 魔术方法

在 Python 中,魔术方法(Magic Methods),又叫特殊方法或双下方法,是以两个下划线(__)开头和结尾的方法。

DaPiCaoMin的博客 997

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

python高级知识之常用的魔术方法

1、__init__()魔术方法 2、__new__()魔术方法 3、__str__()魔术方法 4、__del__()魔术方法 5、__call__()魔术方法 6、__len__()魔术方法 7、__eq__()魔术方法 8、__hash__()魔术方法 9、__getitem__()魔术方法 10、__setitem__()魔术方法 11、__delitem__()魔术方法 12、__delattr__()魔术方法 13、__add__()/__sub__()魔术方法

克里斯蒂亚诺 5006

Python 中的魔术方法

统一接口:让自定义类的行为与内置类型(如列表、字典)保持一致(如len(obj)灵活定制:通过重载运算符、属性访问、迭代逻辑等,实现高度定制化的类(如单例、自定义容器、上下文管理器);隐式调用:无需显式调用,由 Python 解释器自动触发,简化代码。实际开发中,无需记忆所有魔术方法,而是根据需求选择(如实现with用__enter____exit__,实现迭代用__iter____next__),并遵循“最小必要”原则——仅实现需要的魔术方法,避免过度复杂。

Tallbo的博客 1470

【Python】小子!是魔术方法!

各位优快云的朋友们好~本期将揭晓魔术方法与Python的鸭子类型哲学的巧妙绝伦共六期。

https://github.com/ianchen-dev 2305

Python基础:魔术方法Magic Method

经过之前编章的介绍,我们知道在 Python 中,常见的容器类型有: dict, tuple, list, string。其中也提到过可容器和不可变容器的概念。其中 tuple, string 是不可变容器,dict, list 是可变容器。可变容器和不可变容器的区别在于,不可变容器一旦赋值后,不可对其中的某个元素进行修改。当然具体的介绍,可以看回之前的文章,有图文介绍。那么这里先提出一个问题,这些数据结构就够我们开发使用吗?

在技术的广袤天地里,本博客如精准罗盘。剖析前沿科技,深掘代码奥秘,以精炼笔触,带您穿越复杂技术迷宫,速达知识彼岸。 2196
上一篇: Python--二分查找算法
下一篇: Python--魔术方法--上下文管理
鹿夏
博客等级 码龄8年 24粉丝 105原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值