Python Methods: Complete Usage Guide
In Python, methods are functions defined within a class. They are used to define the behavior and functionality of the class, operating on objects of the class and able to access the class’s attributes and other methods.
The usage of the method includes the following aspects:
- Function
- oneself
class MyClass:
def my_method(self, arg1, arg2):
# 方法体
- self
my_obj = MyClass()
my_obj.my_method(arg1_value, arg2_value)
- myself
class MyClass:
class_attr = "Class Attribute"
def my_method(self):
print(self.class_attr) # 访问实例属性
print(MyClass.class_attr) # 访问类属性
- come back
class MyClass:
def my_method(self):
# 方法体
return result
- Static methods and class methods: Apart from regular methods, Python also offers static methods and class methods. Static methods do not require access to instance attributes or class attributes, while class methods can access class attributes but not instance attributes.
class MyClass:
class_attr = "Class Attribute"
@staticmethod
def static_method():
# 静态方法体
@classmethod
def class_method(cls):
print(cls.class_attr) # 访问类属性
The above is the basic usage of methods, but there are also more advanced features such as method overriding and method parameter passing.