Câu hỏi phỏng vấn Python
Câu hỏi

What is the difference between a function decorated with *...

Câu trả lời

In Python, the decorators @staticmethod and @classmethod are used to define methods that are not bound to an instance of a class but are associated with the class itself. While they share some similarities, they serve different purposes and have distinct behaviors.

@staticmethod

A @staticmethod does not take any implicit first argument (neither self nor cls). This means it does not operate on an instance of the class nor the class itself. It behaves like a regular function that has been included in a class's definition. Since it doesn't have access to the class (cls) or the instance (self), it can't modify class state or instance state. This type of method is used for functionality that is logically encapsulated in the class but does not need to interact with class-specific or instance-specific data.

Key Characteristics of @staticmethod:

  • It can be called on an instance or the class.
  • It does not have access to self or cls.
  • It is used for utility functions that could logically be part of the class but do not need to interact with class or instance properties[1][2][3][4][5].

@classmethod

A @classmethod, on the other hand, takes cls as the first implicit argument instead of self. This means it receives the class itself as an argument, not an instance of the class. This allows it to modify the class state that applies across all instances of the class, such as modifying a class variable. @classmethods are often used for factory methods, which instantiate an instance of the class, using different parameters than those provided to the class constructor.

**Key Characteristics of @classmetho...

senior

senior

Gợi ý câu hỏi phỏng vấn

senior

What is the purpose of the single underscore _ variable in Python?

middle

Is it possible to have static methods in Python?

expert

Is there any downside to the -O flag apart from missing on the built-in debugging information?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào