Hướng dẫn how do i pass instance of an object as an argument in a function in python? - làm cách nào để chuyển thể hiện của đối tượng làm đối số trong hàm trong python?

Tôi mới bắt đầu học Python và đang bối rối về cách truyền một ví dụ của một đối tượng như một đối số cho một hàm, dưới đây là một chút mã tôi đã thực hiện và ý tưởng cơ bản là có một nhà để xe, điều này Nhà để xe không chứa ô tô, và bạn có thể thêm xe vào nhà để xe và xem chi tiết của họ.

Show
class Garage:
    cars = []

    def add_car(self, car):
        cars.append(car)

class Car:
    car_name, car_price, car_colour, car_miles, car_owners = "", "", "", "", ""

    def add_new_car(self, garage, name, price, colour, miles, owners):
        car_name = name
        car_price = price
        car_colour = colour
        car_miles = miles
        car_owners = owners

        garage.add_car(self)

def main(argv=None):    
    your_garage = Garage()

    while True:
        print "Your garage contains %d cars!" % len(your_garage.cars)
        print "1) Add a new car\n2) View your car's\n0) Leave the garage"
        user_input = raw_input("Please pick an option: ")

        if user_input == "1":
            add_car(your_garage)
        elif user_input == "2":
            view_cars(your_garage)
        elif user_input == "0":
            quit()

def add_car(garage):
    name = raw_input("Name: ")
    price = raw_input("Price: ")
    colour = raw_input("Colour: ")
    miles = raw_input("Miles: ")
    owners = raw_input("Owners: ")

    car = Car()
    car.add_new_car(garage, name, price, colour, miles, owners)

def view_cars(garage):
    for x in xrange(len(garage.cars)):
        print garage.cars[x].car_name
        print garage.cars[x].car_price
        print garage.cars[x].car_colour
        print garage.cars[x].car_miles
        print garage.cars[x].car_owners

if __name__ == "__main__":
    main()

Mã của tôi có thể rất sai hoặc có thể có một cách dễ dàng để làm điều này, tôi theo cách tôi hình dung nó sẽ là ví dụ mới của chiếc xe tôi đã tạo được thêm vào danh sách những chiếc xe. Tôi có thể làm cái này như thế nào?

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()

Trong ví dụ, có hai lớp xe và xe tải, đối tượng của xe tải lớp được truyền dưới dạng tham số cho phương pháp của xe lớp. Trong phương thức chính () đối tượng của xe được tạo. Sau đó, phương thức add_truck () của xe lớp được gọi và đối tượng của lớp xe tải được truyền dưới dạng tham số.

Đầu ra mẫu của chương trình trên.

2020-11-17T05: 06: 09+05: 302020-11-17T05: 06: 09+05: 30Amit Aroraccothon Lập trình TutororythonPractical Solution 2020-11-17T05:06:09+05:30 Amit Arora Python Programming Tutorial Python Practical Solution

Xem bây giờ hướng dẫn này có một khóa học video liên quan được tạo bởi nhóm Python thực sự. Xem cùng với hướng dẫn bằng văn bản để hiểu sâu hơn về sự hiểu biết của bạn: vượt qua tham chiếu trong Python: Thực tiễn tốt nhất This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Pass by Reference in Python: Best Practices

Sau khi đạt được sự quen thuộc với Python, bạn có thể nhận thấy các trường hợp trong đó các chức năng của bạn không sửa đổi các đối số như bạn có thể mong đợi, đặc biệt là nếu bạn quen thuộc với các ngôn ngữ lập trình khác. Một số ngôn ngữ xử lý các đối số chức năng như các tham chiếu đến các biến hiện có, được gọi là vượt qua bởi tham chiếu. Các ngôn ngữ khác xử lý chúng là giá trị độc lập, một cách tiếp cận được gọi là vượt qua giá trị.references to existing variables, which is known as pass by reference. Other languages handle them as independent values, an approach known as pass by value.

Nếu bạn là một lập trình viên Python trung gian, người muốn hiểu cách xử lý các đối số chức năng đặc biệt của Python, thì hướng dẫn này là dành cho bạn. Bạn sẽ thực hiện các trường hợp sử dụng thực sự của các cấu trúc ngang qua trong Python và tìm hiểu một số thực tiễn tốt nhất để tránh những cạm bẫy với các đối số chức năng của bạn.

Trong hướng dẫn này, bạn sẽ học:

  • Ý nghĩa của việc vượt qua tham chiếu và lý do tại sao bạn muốn làm như vậypass by reference and why you’d want to do so
  • Làm thế nào vượt qua bởi tham chiếu khác với cả hai vượt qua giá trị và cách tiếp cận độc đáo của Pythonpassing by value and Python’s unique approach
  • Cách các đối số chức năng hoạt động trong Pythonfunction arguments behave in Python
  • Cách bạn có thể sử dụng một số loại có thể thay đổi để vượt qua tham chiếu trong Pythonmutable types to pass by reference in Python
  • Thực tiễn tốt nhất là gì để sao chép vượt qua bằng cách tham khảo trong Pythonbest practices are for replicating pass by reference in Python

Xác định vượt qua theo tham chiếu

Trước khi bạn đi sâu vào các chi tiết kỹ thuật của việc truyền qua tài liệu tham khảo, nó rất hữu ích để xem xét kỹ hơn thuật ngữ này bằng cách chia nó thành các thành phần:

  • Pass có nghĩa là cung cấp một đối số cho một chức năng. means to provide an argument to a function.
  • Bằng cách tham khảo có nghĩa là đối số mà bạn chuyển đến hàm là một tham chiếu đến một biến đã tồn tại trong bộ nhớ thay vì một bản sao độc lập của biến đó. means that the argument you’re passing to the function is a reference to a variable that already exists in memory rather than an independent copy of that variable.

Vì bạn đã cung cấp cho chức năng một tham chiếu đến một biến hiện có, tất cả các hoạt động được thực hiện trên tài liệu tham khảo này sẽ ảnh hưởng trực tiếp đến biến mà nó đề cập đến. Hãy cùng xem xét một số ví dụ về cách thức hoạt động trong thực tế.

Dưới đây, bạn sẽ thấy cách truyền các biến bằng cách tham chiếu trong C#. Lưu ý việc sử dụng từ khóa

>>> def main():
...     arg = 4
...     square(arg)
...     print(arg)
...
>>> def square(n):
...     n *= n
...
>>> main()
4
4 trong các dòng được tô sáng:

using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by reference.
        // The value of arg in Main is changed.
        arg = 4;
        squareRef(ref arg);
        Console.WriteLine(arg);
        // Output: 16
    }

    static void squareRef(ref int refParameter)
    {
        refParameter *= refParameter;
    }
}

Như bạn có thể thấy,

>>> def main():
...     arg = 4
...     square(arg)
...     print(arg)
...
>>> def square(n):
...     n *= n
...
>>> main()
4
5 của
>>> def main():
...     arg = 4
...     square(arg)
...     print(arg)
...
>>> def square(n):
...     n *= n
...
>>> main()
4
6 phải được khai báo với từ khóa
>>> def main():
...     arg = 4
...     square(arg)
...     print(arg)
...
>>> def square(n):
...     n *= n
...
>>> main()
4
4 và bạn cũng phải sử dụng từ khóa khi gọi hàm. Sau đó, đối số sẽ được chuyển qua bằng cách tham chiếu và có thể được sửa đổi tại chỗ.

Python không có từ khóa

>>> def main():
...     arg = 4
...     square(arg)
...     print(arg)
...
>>> def square(n):
...     n *= n
...
>>> main()
4
4 hoặc bất cứ điều gì tương đương với nó. Nếu bạn cố gắng sao chép ví dụ trên càng gần càng tốt trong Python, thì bạn sẽ thấy các kết quả khác nhau:

>>>

>>> def main():
...     arg = 4
...     square(arg)
...     print(arg)
...
>>> def square(n):
...     n *= n
...
>>> main()
4

Trong trường hợp này, biến

>>> def main():
...     arg = 4
...     square(arg)
...     print(arg)
...
>>> def square(n):
...     n *= n
...
>>> main()
4
9 không bị thay đổi tại chỗ. Có vẻ như Python coi đối số được cung cấp của bạn là một giá trị độc lập hơn là một tham chiếu đến một biến hiện có. Điều này có nghĩa là Python chuyển các đối số theo giá trị chứ không phải bằng tham chiếu?

Không hẳn. Python chuyển các đối số không bằng cách tham chiếu cũng như giá trị, mà bằng cách gán. Dưới đây, bạn sẽ nhanh chóng khám phá các chi tiết về việc chuyển bằng giá trị và vượt qua bằng cách tham khảo trước khi xem xét kỹ hơn theo cách tiếp cận của Python. Sau đó, bạn sẽ đi qua một số thực tiễn tốt nhất để đạt được sự tương đương của việc vượt qua bằng cách tham khảo trong Python.by assignment. Below, you’ll quickly explore the details of passing by value and passing by reference before looking more closely at Python’s approach. After that, you’ll walk through some best practices for achieving the equivalent of passing by reference in Python.

Tương phản vượt qua bằng cách tham chiếu và vượt qua giá trị

Khi bạn vượt qua các đối số chức năng bằng tham chiếu, các đối số đó chỉ tham khảo các giá trị hiện có. Ngược lại, khi bạn vượt qua các đối số theo giá trị, những đối số đó trở thành bản sao độc lập của các giá trị ban đầu.

Hãy để xem lại ví dụ C#, lần này mà không cần sử dụng từ khóa

>>> def main():
...     arg = 4
...     square(arg)
...     print(arg)
...
>>> def square(n):
...     n *= n
...
>>> main()
4
4. Điều này sẽ khiến chương trình sử dụng hành vi mặc định chuyển bằng giá trị:

using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}

Ở đây, bạn có thể thấy rằng

using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
1 không sửa đổi biến ban đầu. Thay vào đó,
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
2 là một bản sao độc lập của biến ban đầu
>>> def main():
...     arg = 4
...     square(arg)
...     print(arg)
...
>>> def square(n):
...     n *= n
...
>>> main()
4
9. Mặc dù điều đó phù hợp với hành vi mà bạn sẽ thấy trong Python, hãy nhớ rằng Python không chính xác vượt qua giá trị. Hãy để chứng minh điều đó.

Python sườn tích hợp

using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
4 trả về một số nguyên đại diện cho địa chỉ bộ nhớ của đối tượng mong muốn. Sử dụng
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
4, bạn có thể xác minh các xác nhận sau:

  1. Các đối số chức năng ban đầu đề cập đến cùng một địa chỉ với các biến ban đầu của chúng.
  2. Việc chỉ định lại đối số trong hàm cung cấp cho nó một địa chỉ mới trong khi biến ban đầu vẫn chưa được sửa đổi.

Trong ví dụ dưới đây, lưu ý rằng địa chỉ của

using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
6 ban đầu khớp với
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
7 nhưng thay đổi sau khi phân công lại, trong khi địa chỉ của
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
7 không bao giờ thay đổi:

>>>

>>> def main():
...     n = 9001
...     print(f"Initial address of n: {id(n)}")
...     increment(n)
...     print(f"  Final address of n: {id(n)}")
...
>>> def increment(x):
...     print(f"Initial address of x: {id(x)}")
...     x += 1
...     print(f"  Final address of x: {id(x)}")
...
>>> main()
Initial address of n: 140562586057840
Initial address of x: 140562586057840
  Final address of x: 140562586057968
  Final address of n: 140562586057840

Thực tế là các địa chỉ ban đầu của

using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
7 và
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
6 là như nhau khi bạn gọi
>>> def main():
...     n = 9001
...     print(f"Initial address of n: {id(n)}")
...     increment(n)
...     print(f"  Final address of n: {id(n)}")
...
>>> def increment(x):
...     print(f"Initial address of x: {id(x)}")
...     x += 1
...     print(f"  Final address of x: {id(x)}")
...
>>> main()
Initial address of n: 140562586057840
Initial address of x: 140562586057840
  Final address of x: 140562586057968
  Final address of n: 140562586057840
1 chứng minh rằng đối số
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
6 không được truyền bởi giá trị. Mặt khác,
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
7 và
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
6 sẽ có địa chỉ bộ nhớ riêng biệt.

Trước khi bạn tìm hiểu các chi tiết về cách Python xử lý các đối số, hãy để Lôi xem xét một số trường hợp sử dụng thực tế để đi qua bằng cách tham khảo.

Sử dụng các cấu trúc tham chiếu vượt qua

Vượt qua các biến bằng tham chiếu là một trong một số chiến lược bạn có thể sử dụng để thực hiện các mẫu lập trình nhất định. Mặc dù nó hiếm khi cần thiết, nhưng đi qua tham chiếu có thể là một công cụ hữu ích.

Trong phần này, bạn sẽ xem xét ba trong số các mẫu phổ biến nhất mà đi qua bằng cách tham khảo là một cách tiếp cận thực tế. Sau đó, bạn sẽ xem cách bạn có thể thực hiện từng mẫu này với Python.

Tránh các đối tượng trùng lặp

Như bạn đã thấy, việc chuyển một biến theo giá trị sẽ khiến một bản sao của giá trị đó được tạo và lưu trữ trong bộ nhớ. Trong các ngôn ngữ mặc định để truyền theo giá trị, bạn có thể tìm thấy lợi ích hiệu suất từ ​​việc truyền biến bằng cách tham chiếu thay thế, đặc biệt là khi biến chứa rất nhiều dữ liệu. Điều này sẽ rõ ràng hơn khi mã của bạn đang chạy trên các máy bị hạn chế tài nguyên.

Tuy nhiên, trong Python, đây không bao giờ là vấn đề. Bạn sẽ thấy tại sao trong phần tiếp theo.

Trả về nhiều giá trị

Một trong những ứng dụng phổ biến nhất của việc truyền bằng tham chiếu là tạo một hàm làm thay đổi giá trị của các tham số tham chiếu trong khi trả về một giá trị riêng biệt. Bạn có thể sửa đổi ví dụ C# Pass-By-Reference của mình để minh họa kỹ thuật này:

using System;

class Program
{
    static void Main(string[] args)
    {
        int counter = 0;

        // Passing by reference.
        // The value of counter in Main is changed.
        Console.WriteLine(greet("Alice", ref counter));
        Console.WriteLine("Counter is {0}", counter);
        Console.WriteLine(greet("Bob", ref counter));
        Console.WriteLine("Counter is {0}", counter);
        // Output:
        // Hi, Alice!
        // Counter is 1
        // Hi, Bob!
        // Counter is 2
    }

    static string greet(string name, ref int counter)
    {
        string greeting = "Hi, " + name + "!";
        counter++;
        return greeting;
    }
}

Trong ví dụ trên,

>>> def main():
...     n = 9001
...     print(f"Initial address of n: {id(n)}")
...     increment(n)
...     print(f"  Final address of n: {id(n)}")
...
>>> def increment(x):
...     print(f"Initial address of x: {id(x)}")
...     x += 1
...     print(f"  Final address of x: {id(x)}")
...
>>> main()
Initial address of n: 140562586057840
Initial address of x: 140562586057840
  Final address of x: 140562586057968
  Final address of n: 140562586057840
5 trả về một chuỗi lời chào và cũng sửa đổi giá trị của
>>> def main():
...     n = 9001
...     print(f"Initial address of n: {id(n)}")
...     increment(n)
...     print(f"  Final address of n: {id(n)}")
...
>>> def increment(x):
...     print(f"Initial address of x: {id(x)}")
...     x += 1
...     print(f"  Final address of x: {id(x)}")
...
>>> main()
Initial address of n: 140562586057840
Initial address of x: 140562586057840
  Final address of x: 140562586057968
  Final address of n: 140562586057840
6. Bây giờ hãy cố gắng tái tạo điều này càng gần càng tốt trong Python:

>>>

>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     counter += 1
...     return f"Hi, {name}!"
...
>>> main()
Hi, Alice!
Counter is 0
Hi, Bob!
Counter is 0

Thực tế là các địa chỉ ban đầu của

using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
7 và
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
6 là như nhau khi bạn gọi
>>> def main():
...     n = 9001
...     print(f"Initial address of n: {id(n)}")
...     increment(n)
...     print(f"  Final address of n: {id(n)}")
...
>>> def increment(x):
...     print(f"Initial address of x: {id(x)}")
...     x += 1
...     print(f"  Final address of x: {id(x)}")
...
>>> main()
Initial address of n: 140562586057840
Initial address of x: 140562586057840
  Final address of x: 140562586057968
  Final address of n: 140562586057840
1 chứng minh rằng đối số
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
6 không được truyền bởi giá trị. Mặt khác,
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
7 và
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
6 sẽ có địa chỉ bộ nhớ riêng biệt.

Trước khi bạn tìm hiểu các chi tiết về cách Python xử lý các đối số, hãy để Lôi xem xét một số trường hợp sử dụng thực tế để đi qua bằng cách tham khảo.

Sử dụng các cấu trúc tham chiếu vượt qua

>>>

>>> def multiple_return():
...     return 1, 2
...
>>> t = multiple_return()
>>> t  # A tuple
(1, 2)

>>> # You can unpack the tuple into two variables:
>>> x, y = multiple_return()
>>> x
1
>>> y
2

Thực tế là các địa chỉ ban đầu của

using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
7 và
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
6 là như nhau khi bạn gọi
>>> def main():
...     n = 9001
...     print(f"Initial address of n: {id(n)}")
...     increment(n)
...     print(f"  Final address of n: {id(n)}")
...
>>> def increment(x):
...     print(f"Initial address of x: {id(x)}")
...     x += 1
...     print(f"  Final address of x: {id(x)}")
...
>>> main()
Initial address of n: 140562586057840
Initial address of x: 140562586057840
  Final address of x: 140562586057968
  Final address of n: 140562586057840
1 chứng minh rằng đối số
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
6 không được truyền bởi giá trị. Mặt khác,
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
7 và
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
6 sẽ có địa chỉ bộ nhớ riêng biệt.

Trước khi bạn tìm hiểu các chi tiết về cách Python xử lý các đối số, hãy để Lôi xem xét một số trường hợp sử dụng thực tế để đi qua bằng cách tham khảo.

>>>

>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     return f"Hi, {name}!", counter + 1
...
>>> main()
('Hi, Alice!', 1)
Counter is 0
('Hi, Bob!', 1)
Counter is 0

Thực tế là các địa chỉ ban đầu của

using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
7 và
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
6 là như nhau khi bạn gọi
>>> def main():
...     n = 9001
...     print(f"Initial address of n: {id(n)}")
...     increment(n)
...     print(f"  Final address of n: {id(n)}")
...
>>> def increment(x):
...     print(f"Initial address of x: {id(x)}")
...     x += 1
...     print(f"  Final address of x: {id(x)}")
...
>>> main()
Initial address of n: 140562586057840
Initial address of x: 140562586057840
  Final address of x: 140562586057968
  Final address of n: 140562586057840
1 chứng minh rằng đối số
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
6 không được truyền bởi giá trị. Mặt khác,
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
7 và
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
6 sẽ có địa chỉ bộ nhớ riêng biệt.

Trước khi bạn tìm hiểu các chi tiết về cách Python xử lý các đối số, hãy để Lôi xem xét một số trường hợp sử dụng thực tế để đi qua bằng cách tham khảo.reassign your

>>> def main():
...     n = 9001
...     print(f"Initial address of n: {id(n)}")
...     increment(n)
...     print(f"  Final address of n: {id(n)}")
...
>>> def increment(x):
...     print(f"Initial address of x: {id(x)}")
...     x += 1
...     print(f"  Final address of x: {id(x)}")
...
>>> main()
Initial address of n: 140562586057840
Initial address of x: 140562586057840
  Final address of x: 140562586057968
  Final address of n: 140562586057840
6 variable with each call to
>>> def main():
...     n = 9001
...     print(f"Initial address of n: {id(n)}")
...     increment(n)
...     print(f"  Final address of n: {id(n)}")
...
>>> def increment(x):
...     print(f"Initial address of x: {id(x)}")
...     x += 1
...     print(f"  Final address of x: {id(x)}")
...
>>> main()
Initial address of n: 140562586057840
Initial address of x: 140562586057840
  Final address of x: 140562586057968
  Final address of n: 140562586057840
5:

>>>

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
0

Thực tế là các địa chỉ ban đầu của

using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
7 và
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
6 là như nhau khi bạn gọi
>>> def main():
...     n = 9001
...     print(f"Initial address of n: {id(n)}")
...     increment(n)
...     print(f"  Final address of n: {id(n)}")
...
>>> def increment(x):
...     print(f"Initial address of x: {id(x)}")
...     x += 1
...     print(f"  Final address of x: {id(x)}")
...
>>> main()
Initial address of n: 140562586057840
Initial address of x: 140562586057840
  Final address of x: 140562586057968
  Final address of n: 140562586057840
1 chứng minh rằng đối số
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
6 không được truyền bởi giá trị. Mặt khác,
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
7 và
using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
6 sẽ có địa chỉ bộ nhớ riêng biệt.

Trước khi bạn tìm hiểu các chi tiết về cách Python xử lý các đối số, hãy để Lôi xem xét một số trường hợp sử dụng thực tế để đi qua bằng cách tham khảo.

Sử dụng các cấu trúc tham chiếu vượt qua

Vượt qua các biến bằng tham chiếu là một trong một số chiến lược bạn có thể sử dụng để thực hiện các mẫu lập trình nhất định. Mặc dù nó hiếm khi cần thiết, nhưng đi qua tham chiếu có thể là một công cụ hữu ích.

Trong phần này, bạn sẽ xem xét ba trong số các mẫu phổ biến nhất mà đi qua bằng cách tham khảo là một cách tiếp cận thực tế. Sau đó, bạn sẽ xem cách bạn có thể thực hiện từng mẫu này với Python.

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
1

Tránh các đối tượng trùng lặp

  1. Như bạn đã thấy, việc chuyển một biến theo giá trị sẽ khiến một bản sao của giá trị đó được tạo và lưu trữ trong bộ nhớ. Trong các ngôn ngữ mặc định để truyền theo giá trị, bạn có thể tìm thấy lợi ích hiệu suất từ ​​việc truyền biến bằng cách tham chiếu thay thế, đặc biệt là khi biến chứa rất nhiều dữ liệu. Điều này sẽ rõ ràng hơn khi mã của bạn đang chạy trên các máy bị hạn chế tài nguyên., then the output parameter will be set to the resulting integer, and the function will return
    >>> def main():
    ...     counter = 0
    ...     print(greet("Alice", counter))
    ...     print(f"Counter is {counter}")
    ...     print(greet("Bob", counter))
    ...     print(f"Counter is {counter}")
    ...
    >>> def greet(name, counter):
    ...     counter += 1
    ...     return f"Hi, {name}!"
    ...
    >>> main()
    Hi, Alice!
    Counter is 0
    Hi, Bob!
    Counter is 0
    
    0.
  2. Tuy nhiên, trong Python, đây không bao giờ là vấn đề. Bạn sẽ thấy tại sao trong phần tiếp theo., then the output parameter will be set to
    using System;
    
    class Program
    {
        static void Main(string[] args)
        {
            int counter = 0;
    
            // Passing by reference.
            // The value of counter in Main is changed.
            Console.WriteLine(greet("Alice", ref counter));
            Console.WriteLine("Counter is {0}", counter);
            Console.WriteLine(greet("Bob", ref counter));
            Console.WriteLine("Counter is {0}", counter);
            // Output:
            // Hi, Alice!
            // Counter is 1
            // Hi, Bob!
            // Counter is 2
        }
    
        static string greet(string name, ref int counter)
        {
            string greeting = "Hi, " + name + "!";
            counter++;
            return greeting;
        }
    }
    
    4, and the function will return
    >>> def main():
    ...     counter = 0
    ...     print(greet("Alice", counter))
    ...     print(f"Counter is {counter}")
    ...     print(greet("Bob", counter))
    ...     print(f"Counter is {counter}")
    ...
    >>> def greet(name, counter):
    ...     counter += 1
    ...     return f"Hi, {name}!"
    ...
    >>> main()
    Hi, Alice!
    Counter is 0
    Hi, Bob!
    Counter is 0
    
    2.

Trả về nhiều giá trị

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
2

Mã trên, cố gắng chuyển đổi các chuỗi được định dạng khác nhau thành số nguyên thông qua

>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     counter += 1
...     return f"Hi, {name}!"
...
>>> main()
Hi, Alice!
Counter is 0
Hi, Bob!
Counter is 0
3, xuất ra như sau:

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
3

Để thực hiện một chức năng tương tự trong Python, bạn có thể sử dụng nhiều giá trị trả về như bạn đã thấy trước đây:

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
4

>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     counter += 1
...     return f"Hi, {name}!"
...
>>> main()
Hi, Alice!
Counter is 0
Hi, Bob!
Counter is 0
4 này trả về hai giá trị. Giá trị đầu tiên cho biết việc chuyển đổi có thành công hay không và lần thứ hai giữ kết quả (hoặc
>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     counter += 1
...     return f"Hi, {name}!"
...
>>> main()
Hi, Alice!
Counter is 0
Hi, Bob!
Counter is 0
5, trong trường hợp thất bại).

Tuy nhiên, sử dụng chức năng này là một chút lộn xộn vì bạn cần giải nén các giá trị trả về với mỗi cuộc gọi. Điều này có nghĩa là bạn có thể sử dụng chức năng trong câu lệnh

>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     counter += 1
...     return f"Hi, {name}!"
...
>>> main()
Hi, Alice!
Counter is 0
Hi, Bob!
Counter is 0
6:

>>>

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
5

Mặc dù nó thường hoạt động bằng cách trả về nhiều giá trị,

>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     counter += 1
...     return f"Hi, {name}!"
...
>>> main()
Hi, Alice!
Counter is 0
Hi, Bob!
Counter is 0
4 có thể được sử dụng trong kiểm tra điều kiện. Điều đó có nghĩa là bạn có thêm một số việc phải làm.

Bạn có thể tận dụng tính linh hoạt của Python và đơn giản hóa chức năng để trả về một giá trị duy nhất của các loại khác nhau tùy thuộc vào việc chuyển đổi có thành công hay không:

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
6

Với khả năng các chức năng Python trả về các loại dữ liệu khác nhau, giờ đây bạn có thể sử dụng chức năng này trong một câu lệnh có điều kiện. Nhưng bằng cách nào? Bạn sẽ phải gọi hàm trước, gán giá trị trả về của nó và sau đó kiểm tra giá trị?

Bằng cách tận dụng tính linh hoạt của Python, trong các loại đối tượng, cũng như các biểu thức gán mới trong Python 3.8, bạn có thể gọi hàm đơn giản này trong câu lệnh

>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     counter += 1
...     return f"Hi, {name}!"
...
>>> main()
Hi, Alice!
Counter is 0
Hi, Bob!
Counter is 0
6 có điều kiện và nhận giá trị trả về nếu kiểm tra vượt qua:

>>>

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
7

Mặc dù nó thường hoạt động bằng cách trả về nhiều giá trị,

>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     counter += 1
...     return f"Hi, {name}!"
...
>>> main()
Hi, Alice!
Counter is 0
Hi, Bob!
Counter is 0
4 có thể được sử dụng trong kiểm tra điều kiện. Điều đó có nghĩa là bạn có thêm một số việc phải làm.

Bạn có thể tận dụng tính linh hoạt của Python và đơn giản hóa chức năng để trả về một giá trị duy nhất của các loại khác nhau tùy thuộc vào việc chuyển đổi có thành công hay không:assigning return values when using the assignment expression operator(

>>> def multiple_return():
...     return 1, 2
...
>>> t = multiple_return()
>>> t  # A tuple
(1, 2)

>>> # You can unpack the tuple into two variables:
>>> x, y = multiple_return()
>>> x
1
>>> y
2
0) and using the return value directly in Python expressions.

Với khả năng các chức năng Python trả về các loại dữ liệu khác nhau, giờ đây bạn có thể sử dụng chức năng này trong một câu lệnh có điều kiện. Nhưng bằng cách nào? Bạn sẽ phải gọi hàm trước, gán giá trị trả về của nó và sau đó kiểm tra giá trị?

Bằng cách tận dụng tính linh hoạt của Python, trong các loại đối tượng, cũng như các biểu thức gán mới trong Python 3.8, bạn có thể gọi hàm đơn giản này trong câu lệnh >>> def main(): ... counter = 0 ... print(greet("Alice", counter)) ... print(f"Counter is {counter}") ... print(greet("Bob", counter)) ... print(f"Counter is {counter}") ... >>> def greet(name, counter): ... counter += 1 ... return f"Hi, {name}!" ... >>> main() Hi, Alice! Counter is 0 Hi, Bob! Counter is 0 6 có điều kiện và nhận giá trị trả về nếu kiểm tra vượt qua:

Ồ! Phiên bản Python này của

>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     counter += 1
...     return f"Hi, {name}!"
...
>>> main()
Hi, Alice!
Counter is 0
Hi, Bob!
Counter is 0
4 thậm chí còn mạnh hơn phiên bản C#, cho phép bạn sử dụng nó trong các câu lệnh có điều kiện và trong các biểu thức số học.

Với một chút khéo léo, bạn đã sao chép một mô hình chuyển qua cụ thể và hữu ích mà không thực sự truyền cho các đối số bằng cách tham khảo. Trên thực tế, bạn lại một lần nữa gán các giá trị trả về khi sử dụng toán tử biểu thức gán (________ 80) và sử dụng giá trị trả về trực tiếp trong các biểu thức Python.

Cho đến nay, bạn đã học được những gì vượt qua bằng cách tham khảo có nghĩa là, nó khác với việc vượt qua giá trị như thế nào và cách tiếp cận của Python khác với cả hai. Bây giờ bạn đã sẵn sàng để xem xét kỹ hơn về cách Python xử lý các đối số chức năng!

Vượt qua các cuộc tranh luận trong Python

  • Python chuyển các đối số bằng cách chuyển nhượng. Đó là, khi bạn gọi hàm python, mỗi đối số hàm trở thành một biến mà giá trị truyền được gán.
  • Do đó, bạn có thể tìm hiểu các chi tiết quan trọng về cách Python xử lý các đối số chức năng bằng cách hiểu cách thức cơ chế gán hoạt động, ngay cả các chức năng bên ngoài.

Hiểu nhiệm vụ trong Python

Tham khảo ngôn ngữ Python cho các câu lệnh gán cung cấp các chi tiết sau:

  1. Nếu mục tiêu gán là một định danh hoặc tên biến, thì tên này bị ràng buộc với đối tượng. Ví dụ, trong
    >>> def multiple_return():
    ...     return 1, 2
    ...
    >>> t = multiple_return()
    >>> t  # A tuple
    (1, 2)
    
    >>> # You can unpack the tuple into two variables:
    >>> x, y = multiple_return()
    >>> x
    1
    >>> y
    2
    
    1,
    using System;
    
    // Source:
    // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
    class Program
    {
        static void Main(string[] args)
        {
            int arg;
    
            // Passing by value.
            // The value of arg in Main is not changed.
            arg = 4;
            squareVal(arg);
            Console.WriteLine(arg);
            // Output: 4
        }
    
        static void squareVal(int valParameter)
        {
            valParameter *= valParameter;
        }
    }
    
    6 là tên và
    >>> def multiple_return():
    ...     return 1, 2
    ...
    >>> t = multiple_return()
    >>> t  # A tuple
    (1, 2)
    
    >>> # You can unpack the tuple into two variables:
    >>> x, y = multiple_return()
    >>> x
    1
    >>> y
    2
    
    3 là đối tượng.
  2. Nếu tên đã bị ràng buộc với một đối tượng riêng biệt, thì nó sẽ liên kết lại với đối tượng mới. Ví dụ: nếu
    using System;
    
    // Source:
    // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
    class Program
    {
        static void Main(string[] args)
        {
            int arg;
    
            // Passing by value.
            // The value of arg in Main is not changed.
            arg = 4;
            squareVal(arg);
            Console.WriteLine(arg);
            // Output: 4
        }
    
        static void squareVal(int valParameter)
        {
            valParameter *= valParameter;
        }
    }
    
    6 đã
    >>> def multiple_return():
    ...     return 1, 2
    ...
    >>> t = multiple_return()
    >>> t  # A tuple
    (1, 2)
    
    >>> # You can unpack the tuple into two variables:
    >>> x, y = multiple_return()
    >>> x
    1
    >>> y
    2
    
    3 và bạn phát hành
    >>> def multiple_return():
    ...     return 1, 2
    ...
    >>> t = multiple_return()
    >>> t  # A tuple
    (1, 2)
    
    >>> # You can unpack the tuple into two variables:
    >>> x, y = multiple_return()
    >>> x
    1
    >>> y
    2
    
    6, thì tên biến
    using System;
    
    // Source:
    // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
    class Program
    {
        static void Main(string[] args)
        {
            int arg;
    
            // Passing by value.
            // The value of arg in Main is not changed.
            arg = 4;
            squareVal(arg);
            Console.WriteLine(arg);
            // Output: 4
        }
    
        static void squareVal(int valParameter)
        {
            valParameter *= valParameter;
        }
    }
    
    6 được giới hạn lại thành
    >>> def multiple_return():
    ...     return 1, 2
    ...
    >>> t = multiple_return()
    >>> t  # A tuple
    (1, 2)
    
    >>> # You can unpack the tuple into two variables:
    >>> x, y = multiple_return()
    >>> x
    1
    >>> y
    2
    
    8.
  3. Tất cả các đối tượng Python được thực hiện trong một cấu trúc cụ thể. Một trong những thuộc tính của cấu trúc này là một bộ đếm theo dõi số lượng tên đã bị ràng buộc với đối tượng này.

Hãy để ví dụ về ví dụ

>>> def multiple_return():
...     return 1, 2
...
>>> t = multiple_return()
>>> t  # A tuple
(1, 2)

>>> # You can unpack the tuple into two variables:
>>> x, y = multiple_return()
>>> x
1
>>> y
2
1 và kiểm tra điều gì xảy ra khi bạn gán giá trị cho một biến mới:

  1. Nếu một đối tượng đại diện cho giá trị
    >>> def multiple_return():
    ...     return 1, 2
    ...
    >>> t = multiple_return()
    >>> t  # A tuple
    (1, 2)
    
    >>> # You can unpack the tuple into two variables:
    >>> x, y = multiple_return()
    >>> x
    1
    >>> y
    2
    
    3 đã tồn tại, thì nó đã được truy xuất. Nếu không, nó đã tạo ra.
  2. Bộ đếm tham chiếu của đối tượng này được tăng lên.
  3. Một mục được thêm vào không gian tên hiện tại để liên kết định danh
    using System;
    
    // Source:
    // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
    class Program
    {
        static void Main(string[] args)
        {
            int arg;
    
            // Passing by value.
            // The value of arg in Main is not changed.
            arg = 4;
            squareVal(arg);
            Console.WriteLine(arg);
            // Output: 4
        }
    
        static void squareVal(int valParameter)
        {
            valParameter *= valParameter;
        }
    }
    
    6 với đối tượng đại diện cho
    >>> def multiple_return():
    ...     return 1, 2
    ...
    >>> t = multiple_return()
    >>> t  # A tuple
    (1, 2)
    
    >>> # You can unpack the tuple into two variables:
    >>> x, y = multiple_return()
    >>> x
    1
    >>> y
    2
    
    3. Mục nhập này trên thực tế là một cặp giá trị khóa được lưu trữ trong một từ điển! Một đại diện của từ điển đó được trả lại bởi
    >>> def main():
    ...     counter = 0
    ...     print(greet("Alice", counter))
    ...     print(f"Counter is {counter}")
    ...     print(greet("Bob", counter))
    ...     print(f"Counter is {counter}")
    ...
    >>> def greet(name, counter):
    ...     return f"Hi, {name}!", counter + 1
    ...
    >>> main()
    ('Hi, Alice!', 1)
    Counter is 0
    ('Hi, Bob!', 1)
    Counter is 0
    
    3 hoặc
    >>> def main():
    ...     counter = 0
    ...     print(greet("Alice", counter))
    ...     print(f"Counter is {counter}")
    ...     print(greet("Bob", counter))
    ...     print(f"Counter is {counter}")
    ...
    >>> def greet(name, counter):
    ...     return f"Hi, {name}!", counter + 1
    ...
    >>> main()
    ('Hi, Alice!', 1)
    Counter is 0
    ('Hi, Bob!', 1)
    Counter is 0
    
    4.

Bây giờ ở đây, những gì xảy ra nếu bạn phân công lại

using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by value.
        // The value of arg in Main is not changed.
        arg = 4;
        squareVal(arg);
        Console.WriteLine(arg);
        // Output: 4
    }

    static void squareVal(int valParameter)
    {
        valParameter *= valParameter;
    }
}
6 thành một giá trị khác:

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
8

Bộ đếm tham chiếu của đối tượng đại diện cho

>>> def multiple_return():
...     return 1, 2
...
>>> t = multiple_return()
>>> t  # A tuple
(1, 2)

>>> # You can unpack the tuple into two variables:
>>> x, y = multiple_return()
>>> x
1
>>> y
2
3 bị giảm.

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
9

Những kết quả này minh họa mối quan hệ giữa các định danh (tên biến) và các đối tượng Python đại diện cho các giá trị riêng biệt. Khi bạn gán nhiều biến cho cùng một giá trị, Python sẽ tăng bộ đếm tham chiếu cho đối tượng hiện có và cập nhật không gian tên hiện tại thay vì tạo các đối tượng trùng lặp trong bộ nhớ.

Trong phần tiếp theo, bạn sẽ xây dựng dựa trên sự hiểu biết hiện tại của mình về các hoạt động chuyển nhượng bằng cách khám phá cách Python xử lý các đối số chức năng.

Khám phá các đối số chức năng

Đối số chức năng trong Python là các biến cục bộ. Điều đó nghĩa là gì? Địa phương là một trong những phạm vi Python. Các phạm vi này được thể hiện bằng từ điển không gian tên được đề cập trong phần trước. Bạn có thể sử dụng

>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     return f"Hi, {name}!", counter + 1
...
>>> main()
('Hi, Alice!', 1)
Counter is 0
('Hi, Bob!', 1)
Counter is 0
3 và
>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     return f"Hi, {name}!", counter + 1
...
>>> main()
('Hi, Alice!', 1)
Counter is 0
('Hi, Bob!', 1)
Counter is 0
4 để truy xuất từ ​​điển không gian tên địa phương và toàn cầu, tương ứng.local variables. What does that mean? Local is one of Python’s scopes. These scopes are represented by the namespace dictionaries mentioned in the previous section. You can use
>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     return f"Hi, {name}!", counter + 1
...
>>> main()
('Hi, Alice!', 1)
Counter is 0
('Hi, Bob!', 1)
Counter is 0
3 and
>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     return f"Hi, {name}!", counter + 1
...
>>> main()
('Hi, Alice!', 1)
Counter is 0
('Hi, Bob!', 1)
Counter is 0
4 to retrieve the local and global namespace dictionaries, respectively.

Sau khi thực hiện, mỗi hàm có không gian tên cục bộ riêng:

>>>

using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by reference.
        // The value of arg in Main is changed.
        arg = 4;
        squareRef(ref arg);
        Console.WriteLine(arg);
        // Output: 16
    }

    static void squareRef(ref int refParameter)
    {
        refParameter *= refParameter;
    }
}
0

Sử dụng

>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     return f"Hi, {name}!", counter + 1
...
>>> main()
('Hi, Alice!', 1)
Counter is 0
('Hi, Bob!', 1)
Counter is 0
3, bạn có thể chứng minh rằng các đối số chức năng trở thành các biến thường xuyên trong không gian tên cục bộ của hàm. Hãy để thêm một đối số,
class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
02, vào chức năng:

>>>

using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by reference.
        // The value of arg in Main is changed.
        arg = 4;
        squareRef(ref arg);
        Console.WriteLine(arg);
        // Output: 16
    }

    static void squareRef(ref int refParameter)
    {
        refParameter *= refParameter;
    }
}
1

Sử dụng

>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     return f"Hi, {name}!", counter + 1
...
>>> main()
('Hi, Alice!', 1)
Counter is 0
('Hi, Bob!', 1)
Counter is 0
3, bạn có thể chứng minh rằng các đối số chức năng trở thành các biến thường xuyên trong không gian tên cục bộ của hàm. Hãy để thêm một đối số,
class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
02, vào chức năng:

>>>

using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by reference.
        // The value of arg in Main is changed.
        arg = 4;
        squareRef(ref arg);
        Console.WriteLine(arg);
        // Output: 16
    }

    static void squareRef(ref int refParameter)
    {
        refParameter *= refParameter;
    }
}
2

Sử dụng

>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     return f"Hi, {name}!", counter + 1
...
>>> main()
('Hi, Alice!', 1)
Counter is 0
('Hi, Bob!', 1)
Counter is 0
3, bạn có thể chứng minh rằng các đối số chức năng trở thành các biến thường xuyên trong không gian tên cục bộ của hàm. Hãy để thêm một đối số,
class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
02, vào chức năng:

Bạn cũng có thể sử dụng

>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     return f"Hi, {name}!", counter + 1
...
>>> main()
('Hi, Alice!', 1)
Counter is 0
('Hi, Bob!', 1)
Counter is 0
8 để hiển thị cách các đối số chức năng tăng bộ đếm tham chiếu cho một đối tượng:

Các đầu ra tập lệnh trên được tính tham chiếu cho

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
04 đầu tiên bên ngoài, sau đó bên trong
class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
05, cho thấy mức tăng số lượng tham chiếu không phải một, mà là hai!

Điều đó bởi vì, ngoài chính

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
05, cuộc gọi đến
>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     return f"Hi, {name}!", counter + 1
...
>>> main()
('Hi, Alice!', 1)
Counter is 0
('Hi, Bob!', 1)
Counter is 0
8 bên trong
class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
05 cũng nhận được
class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
02 như một đối số. Điều này đặt
class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
02 trong không gian tên địa phương cho
>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     return f"Hi, {name}!", counter + 1
...
>>> main()
('Hi, Alice!', 1)
Counter is 0
('Hi, Bob!', 1)
Counter is 0
8, thêm một tham chiếu bổ sung vào
class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
04.

Bằng cách kiểm tra các không gian tên và số lượng tham chiếu bên trong các hàm, bạn có thể thấy rằng các đối số chức năng hoạt động chính xác giống như các bài tập: Python tạo các ràng buộc trong hàm tên tên cục bộ giữa các định danh và đối tượng Python đại diện cho các giá trị đối số. Mỗi ràng buộc này sẽ tăng bộ đếm tham chiếu đối tượng.

Bây giờ bạn có thể thấy Python vượt qua các đối số bằng cách chuyển nhượng!

>>>

using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by reference.
        // The value of arg in Main is changed.
        arg = 4;
        squareRef(ref arg);
        Console.WriteLine(arg);
        // Output: 16
    }

    static void squareRef(ref int refParameter)
    {
        refParameter *= refParameter;
    }
}
3

Sử dụng

>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     return f"Hi, {name}!", counter + 1
...
>>> main()
('Hi, Alice!', 1)
Counter is 0
('Hi, Bob!', 1)
Counter is 0
3, bạn có thể chứng minh rằng các đối số chức năng trở thành các biến thường xuyên trong không gian tên cục bộ của hàm. Hãy để thêm một đối số,
class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
02, vào chức năng:

  • Bạn cũng có thể sử dụng
    >>> def main():
    ...     counter = 0
    ...     print(greet("Alice", counter))
    ...     print(f"Counter is {counter}")
    ...     print(greet("Bob", counter))
    ...     print(f"Counter is {counter}")
    ...
    >>> def greet(name, counter):
    ...     return f"Hi, {name}!", counter + 1
    ...
    >>> main()
    ('Hi, Alice!', 1)
    Counter is 0
    ('Hi, Bob!', 1)
    Counter is 0
    
    8 để hiển thị cách các đối số chức năng tăng bộ đếm tham chiếu cho một đối tượng:
  • Các đầu ra tập lệnh trên được tính tham chiếu cho
    class Vehicle:
        def __init__(self):
            self.trucks = []
    
        def add_truck(self, truck):
            self.trucks.append(truck)
    
    
    class Truck:
        def __init__(self, color):
            self.color = color
    
        def __repr__(self):
            return "{}".format(self.color)
    
    
    def main():
        v = Vehicle()
        for t in 'Red Blue Black'.split():
            t = Truck(t)
            v.add_truck(t)
        print(v.trucks)
    
    
    if __name__ == "__main__":
        main()
    
    04 đầu tiên bên ngoài, sau đó bên trong
    class Vehicle:
        def __init__(self):
            self.trucks = []
    
        def add_truck(self, truck):
            self.trucks.append(truck)
    
    
    class Truck:
        def __init__(self, color):
            self.color = color
    
        def __repr__(self):
            return "{}".format(self.color)
    
    
    def main():
        v = Vehicle()
        for t in 'Red Blue Black'.split():
            t = Truck(t)
            v.add_truck(t)
        print(v.trucks)
    
    
    if __name__ == "__main__":
        main()
    
    05, cho thấy mức tăng số lượng tham chiếu không phải một, mà là hai!
  • Điều đó bởi vì, ngoài chính
    class Vehicle:
        def __init__(self):
            self.trucks = []
    
        def add_truck(self, truck):
            self.trucks.append(truck)
    
    
    class Truck:
        def __init__(self, color):
            self.color = color
    
        def __repr__(self):
            return "{}".format(self.color)
    
    
    def main():
        v = Vehicle()
        for t in 'Red Blue Black'.split():
            t = Truck(t)
            v.add_truck(t)
        print(v.trucks)
    
    
    if __name__ == "__main__":
        main()
    
    05, cuộc gọi đến
    >>> def main():
    ...     counter = 0
    ...     print(greet("Alice", counter))
    ...     print(f"Counter is {counter}")
    ...     print(greet("Bob", counter))
    ...     print(f"Counter is {counter}")
    ...
    >>> def greet(name, counter):
    ...     return f"Hi, {name}!", counter + 1
    ...
    >>> main()
    ('Hi, Alice!', 1)
    Counter is 0
    ('Hi, Bob!', 1)
    Counter is 0
    
    8 bên trong
    class Vehicle:
        def __init__(self):
            self.trucks = []
    
        def add_truck(self, truck):
            self.trucks.append(truck)
    
    
    class Truck:
        def __init__(self, color):
            self.color = color
    
        def __repr__(self):
            return "{}".format(self.color)
    
    
    def main():
        v = Vehicle()
        for t in 'Red Blue Black'.split():
            t = Truck(t)
            v.add_truck(t)
        print(v.trucks)
    
    
    if __name__ == "__main__":
        main()
    
    05 cũng nhận được
    class Vehicle:
        def __init__(self):
            self.trucks = []
    
        def add_truck(self, truck):
            self.trucks.append(truck)
    
    
    class Truck:
        def __init__(self, color):
            self.color = color
    
        def __repr__(self):
            return "{}".format(self.color)
    
    
    def main():
        v = Vehicle()
        for t in 'Red Blue Black'.split():
            t = Truck(t)
            v.add_truck(t)
        print(v.trucks)
    
    
    if __name__ == "__main__":
        main()
    
    02 như một đối số. Điều này đặt
    class Vehicle:
        def __init__(self):
            self.trucks = []
    
        def add_truck(self, truck):
            self.trucks.append(truck)
    
    
    class Truck:
        def __init__(self, color):
            self.color = color
    
        def __repr__(self):
            return "{}".format(self.color)
    
    
    def main():
        v = Vehicle()
        for t in 'Red Blue Black'.split():
            t = Truck(t)
            v.add_truck(t)
        print(v.trucks)
    
    
    if __name__ == "__main__":
        main()
    
    02 trong không gian tên địa phương cho
    >>> def main():
    ...     counter = 0
    ...     print(greet("Alice", counter))
    ...     print(f"Counter is {counter}")
    ...     print(greet("Bob", counter))
    ...     print(f"Counter is {counter}")
    ...
    >>> def greet(name, counter):
    ...     return f"Hi, {name}!", counter + 1
    ...
    >>> main()
    ('Hi, Alice!', 1)
    Counter is 0
    ('Hi, Bob!', 1)
    Counter is 0
    
    8, thêm một tham chiếu bổ sung vào
    class Vehicle:
        def __init__(self):
            self.trucks = []
    
        def add_truck(self, truck):
            self.trucks.append(truck)
    
    
    class Truck:
        def __init__(self, color):
            self.color = color
    
        def __repr__(self):
            return "{}".format(self.color)
    
    
    def main():
        v = Vehicle()
        for t in 'Red Blue Black'.split():
            t = Truck(t)
            v.add_truck(t)
        print(v.trucks)
    
    
    if __name__ == "__main__":
        main()
    
    04.
  • Bằng cách kiểm tra các không gian tên và số lượng tham chiếu bên trong các hàm, bạn có thể thấy rằng các đối số chức năng hoạt động chính xác giống như các bài tập: Python tạo các ràng buộc trong hàm tên tên cục bộ giữa các định danh và đối tượng Python đại diện cho các giá trị đối số. Mỗi ràng buộc này sẽ tăng bộ đếm tham chiếu đối tượng.

Bây giờ bạn có thể thấy Python vượt qua các đối số bằng cách chuyển nhượng!

>>>

using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by reference.
        // The value of arg in Main is changed.
        arg = 4;
        squareRef(ref arg);
        Console.WriteLine(arg);
        // Output: 16
    }

    static void squareRef(ref int refParameter)
    {
        refParameter *= refParameter;
    }
}
4

Sử dụng

>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     return f"Hi, {name}!", counter + 1
...
>>> main()
('Hi, Alice!', 1)
Counter is 0
('Hi, Bob!', 1)
Counter is 0
3, bạn có thể chứng minh rằng các đối số chức năng trở thành các biến thường xuyên trong không gian tên cục bộ của hàm. Hãy để thêm một đối số,
class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
02, vào chức năng:

Bạn cũng có thể sử dụng

>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     return f"Hi, {name}!", counter + 1
...
>>> main()
('Hi, Alice!', 1)
Counter is 0
('Hi, Bob!', 1)
Counter is 0
8 để hiển thị cách các đối số chức năng tăng bộ đếm tham chiếu cho một đối tượng:

Các đầu ra tập lệnh trên được tính tham chiếu cho class Vehicle: def __init__(self): self.trucks = [] def add_truck(self, truck): self.trucks.append(truck) class Truck: def __init__(self, color): self.color = color def __repr__(self): return "{}".format(self.color) def main(): v = Vehicle() for t in 'Red Blue Black'.split(): t = Truck(t) v.add_truck(t) print(v.trucks) if __name__ == "__main__": main() 04 đầu tiên bên ngoài, sau đó bên trong class Vehicle: def __init__(self): self.trucks = [] def add_truck(self, truck): self.trucks.append(truck) class Truck: def __init__(self, color): self.color = color def __repr__(self): return "{}".format(self.color) def main(): v = Vehicle() for t in 'Red Blue Black'.split(): t = Truck(t) v.add_truck(t) print(v.trucks) if __name__ == "__main__": main() 05, cho thấy mức tăng số lượng tham chiếu không phải một, mà là hai!

Điều đó bởi vì, ngoài chính

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
05, cuộc gọi đến
>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     return f"Hi, {name}!", counter + 1
...
>>> main()
('Hi, Alice!', 1)
Counter is 0
('Hi, Bob!', 1)
Counter is 0
8 bên trong
class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
05 cũng nhận được
class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
02 như một đối số. Điều này đặt
class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
02 trong không gian tên địa phương cho
>>> def main():
...     counter = 0
...     print(greet("Alice", counter))
...     print(f"Counter is {counter}")
...     print(greet("Bob", counter))
...     print(f"Counter is {counter}")
...
>>> def greet(name, counter):
...     return f"Hi, {name}!", counter + 1
...
>>> main()
('Hi, Alice!', 1)
Counter is 0
('Hi, Bob!', 1)
Counter is 0
8, thêm một tham chiếu bổ sung vào
class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
04.

Bằng cách kiểm tra các không gian tên và số lượng tham chiếu bên trong các hàm, bạn có thể thấy rằng các đối số chức năng hoạt động chính xác giống như các bài tập: Python tạo các ràng buộc trong hàm tên tên cục bộ giữa các định danh và đối tượng Python đại diện cho các giá trị đối số. Mỗi ràng buộc này sẽ tăng bộ đếm tham chiếu đối tượng.

using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by reference.
        // The value of arg in Main is changed.
        arg = 4;
        squareRef(ref arg);
        Console.WriteLine(arg);
        // Output: 16
    }

    static void squareRef(ref int refParameter)
    {
        refParameter *= refParameter;
    }
}
5

Bây giờ bạn có thể thấy Python vượt qua các đối số bằng cách chuyển nhượng!

Sao chép vượt qua bằng cách tham khảo với Python

Sau khi kiểm tra các không gian tên trong phần trước, bạn có thể hỏi tại sao

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
13 đã được đề cập như một cách để sửa đổi các biến như thể chúng được thông qua bởi tham chiếu:

using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by reference.
        // The value of arg in Main is changed.
        arg = 4;
        squareRef(ref arg);
        Console.WriteLine(arg);
        // Output: 16
    }

    static void squareRef(ref int refParameter)
    {
        refParameter *= refParameter;
    }
}
6

Sử dụng câu lệnh

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
13 thường lấy đi sự rõ ràng của mã của bạn. Nó có thể tạo ra một số vấn đề, bao gồm cả những vấn đề sau:

Các biến miễn phí, dường như không liên quan đến bất cứ điều gì

Các chức năng mà không có các đối số rõ ràng cho các biến nói trên

Viết các chức năng chấp nhận các đối tượng với các thuộc tính, sau đó hoạt động trực tiếp trên các thuộc tính đó, như trong ví dụ sau:

>>>

using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by reference.
        // The value of arg in Main is changed.
        arg = 4;
        squareRef(ref arg);
        Console.WriteLine(arg);
        // Output: 16
    }

    static void squareRef(ref int refParameter)
    {
        refParameter *= refParameter;
    }
}
7

Lưu ý rằng

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
15 cần được viết để hoạt động trực tiếp trên một thuộc tính, sẽ được sửa đổi mà không cần phải gán lại giá trị trả về.

Nó có giá trị lặp lại rằng bạn nên đảm bảo thuộc tính hỗ trợ chuyển nhượng! Ở đây, ví dụ tương tự với

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
16, có thuộc tính chỉ đọc:

>>>

using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by reference.
        // The value of arg in Main is changed.
        arg = 4;
        squareRef(ref arg);
        Console.WriteLine(arg);
        // Output: 16
    }

    static void squareRef(ref int refParameter)
    {
        refParameter *= refParameter;
    }
}
8

Lưu ý rằng

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
15 cần được viết để hoạt động trực tiếp trên một thuộc tính, sẽ được sửa đổi mà không cần phải gán lại giá trị trả về.

Nó có giá trị lặp lại rằng bạn nên đảm bảo thuộc tính hỗ trợ chuyển nhượng! Ở đây, ví dụ tương tự với

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
16, có thuộc tính chỉ đọc:

>>>

using System;

// Source:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
class Program
{
    static void Main(string[] args)
    {
        int arg;

        // Passing by reference.
        // The value of arg in Main is changed.
        arg = 4;
        squareRef(ref arg);
        Console.WriteLine(arg);
        // Output: 16
    }

    static void squareRef(ref int refParameter)
    {
        refParameter *= refParameter;
    }
}
9

Lưu ý rằng

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
15 cần được viết để hoạt động trực tiếp trên một thuộc tính, sẽ được sửa đổi mà không cần phải gán lại giá trị trả về.

Nó có giá trị lặp lại rằng bạn nên đảm bảo thuộc tính hỗ trợ chuyển nhượng! Ở đây, ví dụ tương tự với class Vehicle: def __init__(self): self.trucks = [] def add_truck(self, truck): self.trucks.append(truck) class Truck: def __init__(self, color): self.color = color def __repr__(self): return "{}".format(self.color) def main(): v = Vehicle() for t in 'Red Blue Black'.split(): t = Truck(t) v.add_truck(t) print(v.trucks) if __name__ == "__main__": main() 16, có thuộc tính chỉ đọc:

Nỗ lực sửa đổi các thuộc tính mà don lồng cho phép sửa đổi dẫn đến

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
17.mapping types. Python’s documentation on mapping types provides some insight into the term:

Ngoài ra, bạn nên chú ý đến các thuộc tính lớp. Chúng sẽ không thay đổi và một thuộc tính thể hiện sẽ được tạo và sửa đổi:

Vì các thuộc tính lớp vẫn không thay đổi khi được sửa đổi thông qua một thể hiện lớp, bạn sẽ cần nhớ tham chiếu thuộc tính thể hiện.

>>>

>>> def main():
...     arg = 4
...     square(arg)
...     print(arg)
...
>>> def square(n):
...     n *= n
...
>>> main()
4
0

Thực hành tốt nhất: Sử dụng từ điển và danh sách

Từ điển trong Python là một loại đối tượng khác với tất cả các loại tích hợp khác. Họ được gọi là loại ánh xạ. Tài liệu Python sườn về các loại ánh xạ cung cấp một số cái nhìn sâu sắc về thuật ngữ:subscriptability and mutability. These characteristics are worthy of a little more explanation, but let’s first take a look at best practices for mimicking pass by reference using Python lists.

Một bản đồ đối tượng ánh xạ các giá trị băm vào các đối tượng tùy ý. Ánh xạ là các đối tượng có thể thay đổi. Hiện tại chỉ có một loại ánh xạ tiêu chuẩn, từ điển. (Nguồn)

>>>

>>> def main():
...     arg = 4
...     square(arg)
...     print(arg)
...
>>> def square(n):
...     n *= n
...
>>> main()
4
1

Hướng dẫn này không bao gồm cách thực hiện một loại ánh xạ tùy chỉnh, nhưng bạn có thể sao chép thẻ bằng cách tham chiếu bằng từ điển khiêm tốn. Ở đây, một ví dụ sử dụng chức năng hoạt động trực tiếp trên các yếu tố từ điển:

Vì bạn đã chỉ định lại một giá trị cho khóa từ điển, hoạt động trên các phần tử từ điển vẫn là một hình thức gán. Với từ điển, bạn có được tính thực tế bổ sung khi truy cập giá trị sửa đổi thông qua cùng một đối tượng từ điển.subscriptable when a subset of its structure can be accessed by index positions:

>>>

>>> def main():
...     arg = 4
...     square(arg)
...     print(arg)
...
>>> def square(n):
...     n *= n
...
>>> main()
4
2

Mặc dù danh sách các loại ánh xạ aren, bạn có thể sử dụng chúng theo cách tương tự như từ điển vì hai đặc điểm quan trọng: khả năng đăng ký và khả năng đột biến. Những đặc điểm này đáng để giải thích thêm một chút, nhưng trước tiên, hãy để xem các thực tiễn tốt nhất để bắt chước vượt qua bằng cách tham khảo bằng danh sách Python.

Để sao chép Pass bằng tham chiếu bằng danh sách, hãy viết một chức năng hoạt động trực tiếp trên các yếu tố danh sách:mutable if its structure can be changed in place rather than requiring reassignment:

>>>

>>> def main():
...     arg = 4
...     square(arg)
...     print(arg)
...
>>> def square(n):
...     n *= n
...
>>> main()
4
3

Vì bạn đã chỉ định lại một giá trị cho một yếu tố trong danh sách, hoạt động trên các yếu tố danh sách vẫn là một hình thức gán. Tương tự như từ điển, danh sách cho phép bạn truy cập giá trị sửa đổi thông qua cùng một đối tượng danh sách.

Bây giờ, hãy để khám phá khả năng đăng ký. Một đối tượng có thể đăng ký khi một tập hợp con của cấu trúc của nó có thể được truy cập bởi các vị trí chỉ mục:

Danh sách, bộ dữ liệu và chuỗi là có thể đăng ký, nhưng các bộ thì không. Cố gắng truy cập vào một yếu tố của một đối tượng không thể đăng ký sẽ tăng

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


class Truck:
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()
18.

Khả năng đột biến là một chủ đề rộng hơn yêu cầu tham chiếu tài liệu và thăm dò bổ sung. Để giữ cho mọi thứ ngắn gọn, một đối tượng có thể thay đổi nếu cấu trúc của nó có thể được thay đổi tại chỗ thay vì yêu cầu phân công lại:

  • Danh sách và bộ có thể thay đổi, cũng như từ điển và các loại ánh xạ khác. Chuỗi và bộ dữ liệu không thể thay đổi. Cố gắng sửa đổi một yếu tố của một đối tượng bất biến sẽ tăng
    class Vehicle:
        def __init__(self):
            self.trucks = []
    
        def add_truck(self, truck):
            self.trucks.append(truck)
    
    
    class Truck:
        def __init__(self, color):
            self.color = color
    
        def __repr__(self):
            return "{}".format(self.color)
    
    
    def main():
        v = Vehicle()
        for t in 'Red Blue Black'.split():
            t = Truck(t)
            v.add_truck(t)
        print(v.trucks)
    
    
    if __name__ == "__main__":
        main()
    
    18.assigning values to variables
  • Sự kết luậnpassed by assignment in Python
  • Python hoạt động khác với các ngôn ngữ hỗ trợ các đối số truyền theo tham chiếu hoặc theo giá trị. Các đối số chức năng trở thành các biến cục bộ được gán cho từng giá trị được truyền cho hàm. Nhưng điều này không ngăn cản bạn đạt được kết quả tương tự mà bạn mong đợi khi chuyển các đối số bằng cách tham khảo bằng các ngôn ngữ khác.returning values is a best practice for replicating pass by reference
  • Trong hướng dẫn này, bạn đã học được:attributes, dictionaries, and lists as alternative best practices

Cách Python xử lý việc gán các giá trị cho các biến

Cách các đối số chức năng được truyền bằng cách chuyển nhượng trong Python

Tại sao các giá trị trả lại là một thực tiễn tốt nhất để sao chép vượt qua bằng cách tham khảo

Cách sử dụng các thuộc tính, từ điển và danh sách như các thực tiễn tốt nhất thay thế This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Pass by Reference in Python: Best Practices

Chúng ta có thể chuyển các đối tượng lớp dưới dạng đối số chức năng trong Python không?

Một hàm có thể lấy nhiều đối số, các đối số này có thể là đối tượng, biến (có cùng loại dữ liệu hoặc khác nhau) và các hàm.Các hàm Python là đối tượng hạng nhất.Trong ví dụ dưới đây, một hàm được gán cho một biến.. Python functions are first class objects. In the example below, a function is assigned to a variable.

Chúng ta có thể truyền một đối tượng làm tham số để gọi một phương thức trong Python không?

Bạn có thể chuyển một đối tượng như một đối số cho một hàm, theo cách thông thường..

Chúng ta có thể chuyển các đối tượng làm đối số cho các hàm thành viên không?

Các đối tượng của một lớp có thể được truyền dưới dạng đối số cho các hàm thành viên cũng như các hàm không phải là tháng theo giá trị hoặc theo tham chiếu. as well as nonmember functions either by value or by reference.

Hai phương pháp chuyển các đối số cho các chức năng trong Python là gì?

"Gọi theo giá trị" và "Call by TÊN" Chiến lược đánh giá cho các đối số, tức là cách các đối số từ một cuộc gọi hàm được truyền đến các tham số của hàm, khác nhau giữa các ngôn ngữ lập trình. The evaluation strategy for arguments, i.e. how the arguments from a function call are passed to the parameters of the function, differs between programming languages.