The @ symbol in Python has a few key uses:
1. Decorators:
-
This is the most common use.
-
Decorators are a powerful way to modify the behavior of functions or classes without directly changing their code.
-
They are placed before the function or class definition.
Pythondef my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper @my_decorator def say_hello(): print("Hello!") say_hello()In this example: -
my_decoratoris a function that takes another function (func)1 as an argument. -@my_decoratorabovesay_hello()is equivalent tosay_hello = my_decorator(say_hello).
2. Matrix Multiplication:
-
In libraries like NumPy,
@is used for matrix multiplication.Pythonimport numpy as np a = np.array([[1, 2], [3, 4]]) b = np.array([[5, 6], [7, 8]]) result = a @ b print(result)
3. String Formatting (f-strings):
-
Inside f-strings,
@can be used to access attributes or methods of an object.Pythonclass MyClass: def __init__(self, name): self.name = name obj = MyClass("Example") print(f"The object's name is: {@obj.name}")
Remember these key uses of the @ symbol in Python.
0 件のコメント:
コメントを投稿