2025年1月3日金曜日

how to use @ in python code

 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.

    Python
    def 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_decorator is a function that takes another function (func)1 as an argument. - @my_decorator above say_hello() is equivalent to say_hello = my_decorator(say_hello).

2. Matrix Multiplication:

  • In libraries like NumPy, @ is used for matrix multiplication.

    Python
    import 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.

    Python
    class 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 件のコメント:

コメントを投稿