python魔术方法

2023-05-03  本文已影响0人  木火应

Python中的魔术方法(Magic Methods),也称为双下划线方法(Double underscore methods)或特殊方法(Special methods),是一些特殊的函数,它们以双下划线开头和结尾,并且具有特殊的行为和用途。这些魔术方法可以帮助我们自定义类的行为,使得我们的类可以像内置类型一样使用,例如可以进行算术运算、比较、迭代、索引等操作。

以下是一些常用的魔术方法:

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

p = Point(1, 2)
print(p.x, p.y)  # 输出: 1 2


# __str__和__repr__示例
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"{self.name} is {self.age} years old"

    def __repr__(self):
        return f"Person('{self.name}', {self.age})"

p = Person("Alice", 25)
print(str(p))  # 输出: Alice is 25 years old
print(repr(p))  # 输出: Person('Alice', 25)


# __len__示例
class MyList:
    def __init__(self, items):
        self.items = items

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

l = MyList([1, 2, 3, 4])
print(len(l))  # 输出: 4


# __getitem__和__setitem__示例
class MyList:
    def __init__(self, items):
        self.items = items

    def __getitem__(self, index):
        return self.items[index]

    def __setitem__(self, index, value):
        self.items[index] = value

l = MyList([1, 2, 3, 4])
print(l[2])  # 输出: 3
l[2] = 5
print(l[2])  # 输出: 5


# __contains__示例
class MyList:
    def __init__(self, items):
        self.items = items

    def __contains__(self, item):
        return item in self.items

l = MyList([1, 2, 3, 4])
print(2 in l)  # 输出: True
print(5 in l)  # 输出: False


# __add__示例
class MyList:
    def __init__(self, items):
        self.items = items

    def __add__(self, other):
        return MyList(self.items + other.items)

l1 = MyList([1, 2, 3])
l2 = MyList([4, 5, 6])
l3 = l1 + l2
print(l3.items)  # 输出: [1, 2, 3, 4, 5, 6]


# __lt__和__eq__示例
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __lt__(self, other):
        return self.age < other.age

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

p1 = Person("Alice", 25)
p2 = Person("Bob", 30)
p3 = Person("Charlie", 25)
print(p1 < p2)  # 输出: True
print(p1 == p3)  # 输出: True

# __iter__和__next__示例
class MyRange:
    def __init__(self, start, end):
        self.start = start
        self.end = end

    def __iter__(self):
        return self

    def __next__(self):
        if self.start >= self.end:
            raise StopIteration
        value = self.start
        self.start += 1
        return value

r = MyRange(0, 5)
for i in r:
    print(i)  # 输出: 0 1 2 3 4

# __enter__和__exit__示例
class DatabaseConnection:
    def __init__(self, db_url):
        self.db_url = db_url

    def __enter__(self):
        self.connection = open(self.db_url)
        return self.connection

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.connection.close()

# 使用 with 语句打开数据库连接,并在结束时自动关闭连接
with DatabaseConnection('example.db') as conn:
    # 执行一些操作
    cursor = conn.cursor()
    cursor.execute('SELECT * FROM users')
    rows = cursor.fetchall()
    print(rows)

上一篇 下一篇

猜你喜欢

热点阅读