【英文】Python3方法的重写

Introduction

Notes on method overwriting in Python3.

Overwriting the Constructor Method

  • Methods beginning and ending with __ are called constructor methods.

Initialization

  • The __init__() method is automatically executed when an object is created.
1
2
3
4
5
class ClassName:
def __init__(self):
...

variable_name = ClassName()

Destruction

  • The __del__() method is automatically executed when an object is destroyed.
1
2
3
4
5
class ClassName:
def __init__(self):
...

del variable_name

Overwriting Operators

  • Operator overloading refers to associating operators with class methods, with each operator corresponding to a specific built-in method.

Object Addition

1
2
3
4
5
6
7
8
class ClassName:
def __add__(self):
...

a = ClassName()
b = ClassName()

a + b

Object Subtraction

1
2
3
4
5
6
7
8
class ClassName:
def __sub__(self):
...

a = ClassName()
b = ClassName()

a - b

Object Multiplication

1
2
3
4
5
6
7
8
class ClassName:
def __mul__(self):
...

a = ClassName()
b = ClassName()

a * b

Object Division

1
2
3
4
5
6
7
8
class ClassName:
def __div__(self):
...

a = ClassName()
b = ClassName()

a / b

Object Modulus

1
2
3
4
5
6
7
8
class ClassName:
def __mod__(self):
...

a = ClassName()
b = ClassName()

a % b

Object Greater Than

1
2
3
4
5
6
7
8
class ClassName:
def __gt__(self):
...

a = ClassName()
b = ClassName()

a > b

Object Greater Than or Equal To

1
2
3
4
5
6
7
8
class ClassName:
def __ge__(self):
...

a = ClassName()
b = ClassName()

a >= b

Object Less Than

1
2
3
4
5
6
7
8
class ClassName:
def __lt__(self):
...

a = ClassName()
b = ClassName()

a < b

Object Less Than or Equal To

1
2
3
4
5
6
7
8
class ClassName:
def __le__(self):
...

a = ClassName()
b = ClassName()

a <= b

Object Equality

1
2
3
4
5
6
7
8
class ClassName:
def __eq__(self):
...

a = ClassName()
b = ClassName()

a == b

Object Inequality

1
2
3
4
5
6
7
8
class ClassName:
def __ne__(self):
...

a = ClassName()
b = ClassName()

a != b
1
2
3
4
5
6
7
class ClassName:
def __repr__(self):
...

a = ClassName()

repr(a)
1
2
3
4
5
6
7
class ClassName:
def __str__(self):
...

a = ClassName()

print(a)

Object Indexing

1
2
3
4
5
6
7
class ClassName:
def __getitem__(self):
...

a = ClassName()

a[0]

Object Index Assignment

1
2
3
4
5
6
7
class ClassName:
def __setitem__(self):
...

a = ClassName()

a[0] = 0

Object Index and Slice Deletion

1
2
3
4
5
6
7
class ClassName:
def __delitem__(self):
...

a = ClassName()

del a[0]

Completion