1. Introduction
Python is an object-oriented programming language that allows us to organize our code by defining classes (Class) and objects (Objects). In object-oriented programming, a method is a function associated with an object that defines the behavior of an object. This article will introduce in detail the definition and call of methods in Python, helping readers to deeply understand the core concepts of object-oriented programming.
2. Basics of classes and objects
In Python, a class is a blueprint for creating an object, which defines the properties and methods of an object. Objects are specific instances created based on the class. Here is a simple class definition example:
class Car: def __init__(self, brand, model): = brand = model
In this example,Car
is a class that has two properties:brand
(Brand) andmodel
(model).__init__
is a special method called a constructor, which is used to initialize the state of an object.
3. Method definition
In the class, except__init__
In addition to methods, we can also define other methods to describe the behavior of an object. These methods usuallyself
As the first parameter,self
Represents an instance of the current object. The following is inCar
An example of defining a method in a class:
class Car: def __init__(self, brand, model): = brand = model def start_engine(self): print(f"The {} by {} has started.")
In this example,start_engine
is a method that defines the behavior of a car starting engine.self
Parameters allow this method to access and modify the object's properties.
4. Method call
After defining the class and method, we can create an object and call its methods. Here's how to create itCar
Object and callstart_engine
Example of method:
my_car = Car("Tesla", "Model S") my_car.start_engine()
In this example, we first create aCar
Objectmy_car
, and then it's calledstart_engine
method. The output will be: "The Model S by Tesla has started."
5. Class methods and static methods
In addition to the instance method (byself
Python also supports class methods and static methods:
-
Class Methods:use
@classmethod
Decorators define their first parameter is the class itself, usuallycls
express. -
Static method:use
@staticmethod
Decorators are defined, they do not require references to classes or instances.
Here are examples of class methods and static methods:
class Car: def __init__(self, brand, model): = brand = model @classmethod def get_class_info(cls): print(f"Class: {cls.__name__}") @staticmethod def check_speed(speed): print(f"Speed: {speed} km/h") # Create a Car objectmy_car = Car("Toyota", "Corolla") # Call class methodCar.get_class_info() # Call static methodsCar.check_speed(120)
6. Parameter pass of method
The method can receive parameters, which can be positional parameters, keyword parameters, default parameters, variable position parameters, and variable keyword parameters. Here is an example of parameter passing:
class Car: def __init__(self, brand, model): = brand = model def drive(self, distance, speed=60): print(f"Driving {distance} km at {speed} km/h") def drive_to(self, destination, **kwargs): print(f"Driving to {destination} with settings {kwargs}") # Call the drive methodmy_car.drive(100) # Call the drive method and specify the speedmy_car.drive(200, speed=80) # Call the drive_to method and pass keyword parametersmy_car.drive_to("Beijing", distance=1000, speed=100)
7. The return value of the method
The method can have a return value or no. If the method does not return a value, the default returnNone
. Here is an example of the method return value:
class Calculator: def add(self, a, b): return a + b def multiply(self, a, b): return a * b # Create Calculator objectcalc = Calculator() # Call the method and get the return valueresult = (5, 3) print(f"The sum is: {result}") product = (4, 5) print(f"The product is: {product}")
Summarize
This is the end of this article about method definitions and method calls in Python. For more related Python method definitions and method calls, please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!