@staticmethod: This decorator is used to define a static method in a class. A static method is a method that can be called on the class itself rather than on an instance of the class. Here's an example:
class MyClass:
@staticmethod
def my_static_method():
print("This is a static method")
@classmethod: This decorator is used to define a class method in a class. A class method is a method that takes the class itself as its first argument rather than an instance of the class. Here's an example:
class MyClass:
class_var = "Hello"
@classmethod
def my_class_method(cls):
print(cls.class_var)
@property: This decorator is used to define a method as a property of a class. Properties allow you to access and set the value of an attribute of an instance of the class without explicitly calling a getter or setter method. Here's an example:
class MyClass:
def __init__(self):
self._x = 0
@property
def x(self):
return self._x
@x.setter
def x(self, value):
if value < 0:
raise ValueError("Value must be non-negative")
self._x = value
@log_calls: This decorator can be used to log all calls to a function. Here's an example:
def log_calls(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with args: {args}, kwargs: {kwargs}")
result = func(*args, **kwargs)
print(f"Finished {func.__name__}")
return result
return wrapper
@log_calls
def my_function(x, y):
return x + y
@cache: This decorator can be used to cache the results of a function so that the function doesn't need to be called again with the same arguments. Here's an example:
def cache(func):
results = {}
def wrapper(*args):
if args in results:
return results[args]
result = func(*args)
results[args] = result
return result
return wrapper
@cache
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
0 Comments:
Post a Comment