Hướng dẫn how to create multiple classes in python - cách tạo nhiều lớp trong python

Nói đúng ra, câu trả lời này không phải là một câu trả lời cho câu hỏi cuối cùng. Tuy nhiên, đó là một cách để làm cho cuộc sống của bạn dễ dàng hơn một chút.

Show

Cân nhắc việc tạo một lớp mẫu của lớp (Tôi đang sử dụng thuật ngữ này một cách lỏng lẻo; không có điều đó trong Python) mà

class CorporateActions(KwargAttrs):
    def __init__(self, stock_splits , cash_dividends):
        super().__init__(**locals())

ca = CorporateActions(stock_splits = StockSplits(), cash_dividends = CashDividends() )
2 hoạt động cho bạn. Như thế này:

class KwargAttrs():
    def __init__(self, **kwargs):
        for k,v in kwargs.items():
            setattr(self, k, v)
    def _update(self, **kwargs):
        args_dict = {k:(kwargs[k] if k in kwargs else self.__dict__[k]) for k in self.__dict__} 
        self.__dict__.update(args_dict)

Lớp này sử dụng mọi đối số từ khóa được cung cấp làm thuộc tính đối tượng. Sử dụng nó theo cách này:

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())

Sử dụng một phương thức như thế này, bạn không cần phải đi qua danh sách đối số và gán mọi thuộc tính đối tượng; Nó xảy ra tự động.

Chúng tôi giới thiệu mọi thứ bạn cần để thực hiện trong phương thức

class CorporateActions(KwargAttrs):
    def __init__(self, stock_splits , cash_dividends):
        super().__init__(**locals())

ca = CorporateActions(stock_splits = StockSplits(), cash_dividends = CashDividends() )
2 với các cuộc gọi phương thức đến lớp cha qua
class CorporateActions(KwargAttrs):
    def __init__(self, stock_splits , cash_dividends):
        super().__init__(**locals())

ca = CorporateActions(stock_splits = StockSplits(), cash_dividends = CashDividends() )
4. Chúng tôi làm điều này bởi vì
class CorporateActions(KwargAttrs):
    def __init__(self, stock_splits , cash_dividends):
        super().__init__(**locals())

ca = CorporateActions(stock_splits = StockSplits(), cash_dividends = CashDividends() )
5 trả về
class CorporateActions(KwargAttrs):
    def __init__(self, stock_splits , cash_dividends):
        super().__init__(**locals())

ca = CorporateActions(stock_splits = StockSplits(), cash_dividends = CashDividends() )
6 Mỗi biến trong không gian tên hiện tại của hàm, vì vậy bạn cần 1.) nắm bắt không gian tên đó trước khi bất kỳ công việc nào khác gây ô nhiễm và 2.) Cập nhật không gian tên trong trường hợp bất kỳ công việc nào thay đổi giá trị đối số.

Cuộc gọi đến

class CorporateActions(KwargAttrs):
    def __init__(self, stock_splits , cash_dividends):
        super().__init__(**locals())

ca = CorporateActions(stock_splits = StockSplits(), cash_dividends = CashDividends() )
7 là tùy chọn, nhưng các giá trị của các đối số được cung cấp sẽ không được cập nhật nếu có gì đó được thực hiện với chúng sau cuộc gọi đến
class CorporateActions(KwargAttrs):
    def __init__(self, stock_splits , cash_dividends):
        super().__init__(**locals())

ca = CorporateActions(stock_splits = StockSplits(), cash_dividends = CashDividends() )
8 (nghĩa là bạn thay đổi các giá trị bằng cách sử dụng
class CorporateActions(KwargAttrs):
    def __init__(self, stock_splits , cash_dividends):
        super().__init__(**locals())

ca = CorporateActions(stock_splits = StockSplits(), cash_dividends = CashDividends() )
9, giá trị) ý kiến).

Bạn có thể tiếp tục sử dụng lớp này như vậy:

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())

Như đã đề cập trong các câu trả lời khác, bạn có thể tạo một thùng chứa cho các lớp khác của chúng tôi, nhưng bạn thậm chí có thể làm điều đó bằng cách sử dụng cùng một lớp mẫu này:

class CorporateActions(KwargAttrs):
    def __init__(self, stock_splits , cash_dividends):
        super().__init__(**locals())

ca = CorporateActions(stock_splits = StockSplits(), cash_dividends = CashDividends() )

Đôi khi bạn cần viết một lớp Python cung cấp nhiều cách để xây dựng các đối tượng. Nói cách khác, bạn muốn một lớp thực hiện nhiều hàm tạo. Loại lớp này có ích khi bạn cần tạo các phiên bản bằng các loại hoặc số lượng đối số khác nhau. Có các công cụ để cung cấp nhiều hàm tạo sẽ giúp bạn viết các lớp linh hoạt có thể thích ứng với nhu cầu thay đổi.multiple constructors. This kind of class comes in handy when you need to create instances using different types or numbers of arguments. Having the tools to provide multiple constructors will help you write flexible classes that can adapt to changing needs.

Trong Python, có một số kỹ thuật và công cụ mà bạn có thể sử dụng để xây dựng các lớp, bao gồm mô phỏng nhiều hàm tạo thông qua các đối số tùy chọn, tùy chỉnh tạo thể hiện thông qua các phương thức lớp và thực hiện công văn đặc biệt với các trình trang trí. Nếu bạn muốn tìm hiểu về các kỹ thuật và công cụ này, thì hướng dẫn này là dành cho bạn.

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

  • Sử dụng các đối số tùy chọn và kiểm tra loại để mô phỏng nhiều hàm tạooptional arguments and type checking to simulate multiple constructors
  • Viết nhiều hàm tạo bằng cách sử dụng trình trang trí
    >>> # Define a Person class
    >>> class Person:
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    
    0 tích hợp
    >>> # Define a Person class
    >>> class Person:
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    
    0
    decorator
  • Quá tải các hàm tạo lớp của bạn bằng cách sử dụng trình trang trí
    >>> # Define a Person class
    >>> class Person:
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    
    1
    >>> # Define a Person class
    >>> class Person:
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    
    1
    decorator

Bạn cũng sẽ nhận được một cái nhìn dưới mui xe tại cách Python bên trong xây dựng các trường hợp của một lớp thông thường và cách một số lớp thư viện tiêu chuẩn cung cấp nhiều hàm tạo.constructs instances of a regular class and how some standard-library classes provide multiple constructors.

Để tận dụng tối đa hướng dẫn này, bạn nên có kiến ​​thức cơ bản về lập trình hướng đối tượng và hiểu cách xác định các phương thức lớp với

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
0. Bạn cũng nên có kinh nghiệm làm việc với các nhà trang trí trong Python.

Các lớp học khởi tạo ở Python

Python hỗ trợ lập trình hướng đối tượng với các lớp đơn giản để tạo và sử dụng. Các lớp Python cung cấp các tính năng mạnh mẽ có thể giúp bạn viết phần mềm tốt hơn. Các lớp giống như bản thiết kế cho các đối tượng, còn được gọi là trường hợp. Theo cùng một cách mà bạn có thể xây dựng một số ngôi nhà từ một bản thiết kế duy nhất, bạn có thể xây dựng một số trường hợp từ một lớp.classes that are straightforward to create and use. Python classes offer powerful features that can help you write better software. Classes are like blueprints for objects, also known as instances. In the same way that you can build several houses from a single blueprint, you can build several instances from a class.

Để xác định một lớp trong Python, bạn cần sử dụng từ khóa

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
3 theo sau là tên lớp:

>>>

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...

Python có một bộ phương pháp đặc biệt phong phú mà bạn có thể sử dụng trong các lớp học của mình. Python ngầm gọi các phương thức đặc biệt để tự động thực hiện nhiều hoạt động khác nhau trên các trường hợp. Có các phương pháp đặc biệt để làm cho các đối tượng của bạn trở nên dễ dàng, cung cấp một biểu diễn chuỗi phù hợp cho các đối tượng của bạn, khởi tạo các thuộc tính thể hiện và nhiều hơn nữa.

Một phương pháp đặc biệt khá phổ biến là

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
4. Phương pháp này cung cấp những gì được gọi là trình khởi tạo thể hiện trong Python. Phương thức này Công việc là để khởi tạo các thuộc tính thể hiện với các giá trị phù hợp khi bạn khởi tạo một lớp nhất định.instance initializer in Python. This method’s job is to initialize instance attributes with appropriate values when you instantiate a given class.

Trong

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
5, đối số đầu tiên của phương thức
>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
4 được gọi là
>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
7. Đối số này giữ đối tượng hoặc thể hiện hiện tại, được truyền ngầm trong cuộc gọi phương thức. Đối số này là phổ biến cho mọi phương thức thể hiện trong Python. Đối số thứ hai của
>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
4 được gọi là
>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
9 và sẽ giữ tên người đó dưới dạng chuỗi.

Khi bạn đã xác định một lớp, bạn có thể bắt đầu khởi tạo nó. Nói cách khác, bạn có thể bắt đầu tạo các đối tượng của lớp đó. Để làm điều này, bạn sẽ sử dụng một cú pháp quen thuộc. Chỉ cần gọi lớp bằng cách sử dụng một cặp dấu ngoặc đơn (

>>> # Instantiating Person
>>> john = Person("John Doe")
>>> john.name
'John Doe'
0), đó là cùng một cú pháp mà bạn sử dụng để gọi bất kỳ chức năng Python nào:instantiating it. In other words, you can start creating objects of that class. To do this, you’ll use a familiar syntax. Just call the class using a pair of parentheses (
>>> # Instantiating Person
>>> john = Person("John Doe")
>>> john.name
'John Doe'
0), which is the same syntax that you use to call any Python function:

>>>

>>> # Instantiating Person
>>> john = Person("John Doe")
>>> john.name
'John Doe'

Python có một bộ phương pháp đặc biệt phong phú mà bạn có thể sử dụng trong các lớp học của mình. Python ngầm gọi các phương thức đặc biệt để tự động thực hiện nhiều hoạt động khác nhau trên các trường hợp. Có các phương pháp đặc biệt để làm cho các đối tượng của bạn trở nên dễ dàng, cung cấp một biểu diễn chuỗi phù hợp cho các đối tượng của bạn, khởi tạo các thuộc tính thể hiện và nhiều hơn nữa.class constructor. Calling a class, like you did with

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
5, triggers Python’s class instantiation process, which internally runs in two steps:

  1. Một phương pháp đặc biệt khá phổ biến là
    >>> # Define a Person class
    >>> class Person:
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    
    4. Phương pháp này cung cấp những gì được gọi là trình khởi tạo thể hiện trong Python. Phương thức này Công việc là để khởi tạo các thuộc tính thể hiện với các giá trị phù hợp khi bạn khởi tạo một lớp nhất định.
    a new instance of the target class.
  2. Trong
    >>> # Define a Person class
    >>> class Person:
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    
    5, đối số đầu tiên của phương thức
    >>> # Define a Person class
    >>> class Person:
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    
    4 được gọi là
    >>> # Define a Person class
    >>> class Person:
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    
    7. Đối số này giữ đối tượng hoặc thể hiện hiện tại, được truyền ngầm trong cuộc gọi phương thức. Đối số này là phổ biến cho mọi phương thức thể hiện trong Python. Đối số thứ hai của
    >>> # Define a Person class
    >>> class Person:
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    
    4 được gọi là
    >>> # Define a Person class
    >>> class Person:
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    
    9 và sẽ giữ tên người đó dưới dạng chuỗi.
    the instance with suitable instance attribute values.

Khi bạn đã xác định một lớp, bạn có thể bắt đầu khởi tạo nó. Nói cách khác, bạn có thể bắt đầu tạo các đối tượng của lớp đó. Để làm điều này, bạn sẽ sử dụng một cú pháp quen thuộc. Chỉ cần gọi lớp bằng cách sử dụng một cặp dấu ngoặc đơn (

>>> # Instantiating Person
>>> john = Person("John Doe")
>>> john.name
'John Doe'
0), đó là cùng một cú pháp mà bạn sử dụng để gọi bất kỳ chức năng Python nào:

Trong Python, tên lớp cung cấp những gì các ngôn ngữ khác, chẳng hạn như C ++ và Java, gọi hàm tạo lớp. Gọi một lớp, giống như bạn đã làm với

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
5, kích hoạt quá trình khởi tạo lớp Python, trong hai bước chạy trong hai bước:

Tạo một thể hiện mới của lớp đích.

Khởi tạo thể hiện với các giá trị thuộc tính thể hiện phù hợp.

Để tiếp tục với ví dụ trên, giá trị mà bạn chuyển dưới dạng đối số cho

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
5 được chuyển nội bộ đến
>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
4 và sau đó được gán cho thuộc tính thể hiện
>>> # Instantiating Person
>>> john = Person("John Doe")
>>> john.name
'John Doe'
4. Bằng cách này, bạn khởi tạo phiên bản người của bạn,
>>> # Instantiating Person
>>> john = Person("John Doe")
>>> john.name
'John Doe'
5, với dữ liệu hợp lệ mà bạn có thể xác nhận bằng cách truy cập
>>> # Instantiating Person
>>> john = Person("John Doe")
>>> john.name
'John Doe'
4. Thành công!
>>> # Instantiating Person
>>> john = Person("John Doe")
>>> john.name
'John Doe'
7 thực sự là tên của anh ấy.

Để tóm tắt những gì bạn đã học được cho đến nay, quá trình khởi tạo Python, bắt đầu khi bạn gọi một lớp với các đối số thích hợp. Sau đó, quá trình chạy qua hai bước: tạo đối tượng với phương thức

>>> # Instantiating Person
>>> john = Person("John Doe")
>>> john.name
'John Doe'
8 và khởi tạo đối tượng với phương thức
>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
4.

Bây giờ bạn đã biết về hành vi nội bộ này của Python, bạn đã sẵn sàng tìm hiểu về việc cung cấp nhiều nhà xây dựng trong các lớp học của bạn. Nói cách khác, bạn sẽ cung cấp nhiều cách để xây dựng các đối tượng của một lớp Python nhất định.multiple constructors in your classes. In other words, you’ll provide multiple ways to construct objects of a given Python class.

Xác định nhiều hàm tạo lớp

Đôi khi, bạn muốn viết một lớp cho phép bạn xây dựng các đối tượng bằng các đối số của các loại dữ liệu khác nhau hoặc thậm chí một số lượng đối số khác nhau. Một cách để đạt được điều này là bằng cách cung cấp nhiều hàm tạo trong lớp. Mỗi hàm tạo sẽ cho phép bạn tạo các phiên bản của lớp bằng cách sử dụng một tập hợp các đối số khác nhau.

Một số ngôn ngữ lập trình, chẳng hạn như C ++, C#và Java, hỗ trợ những gì được gọi là quá tải chức năng hoặc phương pháp. Tính năng này cho phép bạn cung cấp nhiều hàm tạo lớp vì nó cho phép bạn tạo nhiều chức năng hoặc phương thức có cùng tên và các triển khai khác nhau.

Quá tải phương thức có nghĩa là tùy thuộc vào cách bạn gọi phương thức trong tay, ngôn ngữ sẽ chọn triển khai phù hợp để chạy. Vì vậy, phương pháp của bạn có thể thực hiện các nhiệm vụ khác nhau theo ngữ cảnh của cuộc gọi.

Thật không may, Python không hỗ trợ chức năng quá tải trực tiếp. Các lớp Python giữ tên phương thức trong một từ điển nội bộ được gọi là

# greet.py

class Greeter:
    def say_hello(self):
        print("Hello, World")

    def say_hello(self):
        print("Hello, Pythonista")
9, giữ không gian tên lớp. Giống như bất kỳ từ điển Python nào,
# greet.py

class Greeter:
    def say_hello(self):
        print("Hello, World")

    def say_hello(self):
        print("Hello, Pythonista")
9 có thể có các khóa lặp lại, vì vậy bạn có thể có nhiều phương thức có cùng tên trong một lớp nhất định. Nếu bạn cố gắng làm như vậy, thì Python sẽ chỉ nhớ lần thực hiện cuối cùng của phương thức:

# greet.py

class Greeter:
    def say_hello(self):
        print("Hello, World")

    def say_hello(self):
        print("Hello, Pythonista")

Trong ví dụ này, bạn tạo

>>> from greet import Greeter

>>> greeter = Greeter()

>>> greeter.say_hello()
Hello, Pythonista

>>> Greeter.__dict__
mappingproxy({..., 'say_hello': , ...})
1 như một lớp Python với hai phương thức. Cả hai phương pháp đều có cùng tên, nhưng chúng có triển khai hơi khác nhau.

Để tìm hiểu những gì xảy ra khi hai phương thức có cùng tên, hãy lưu lớp của bạn vào tệp

>>> from greet import Greeter

>>> greeter = Greeter()

>>> greeter.say_hello()
Hello, Pythonista

>>> Greeter.__dict__
mappingproxy({..., 'say_hello': , ...})
2 trong thư mục làm việc của bạn và chạy mã sau trong phiên tương tác:

>>>

>>> from greet import Greeter

>>> greeter = Greeter()

>>> greeter.say_hello()
Hello, Pythonista

>>> Greeter.__dict__
mappingproxy({..., 'say_hello': , ...})

Trong ví dụ này, bạn gọi

>>> from greet import Greeter

>>> greeter = Greeter()

>>> greeter.say_hello()
Hello, Pythonista

>>> Greeter.__dict__
mappingproxy({..., 'say_hello': , ...})
3 vào
>>> from greet import Greeter

>>> greeter = Greeter()

>>> greeter.say_hello()
Hello, Pythonista

>>> Greeter.__dict__
mappingproxy({..., 'say_hello': , ...})
4, đây là một ví dụ của lớp
>>> from greet import Greeter

>>> greeter = Greeter()

>>> greeter.say_hello()
Hello, Pythonista

>>> Greeter.__dict__
mappingproxy({..., 'say_hello': , ...})
1. Bạn nhận được
>>> from greet import Greeter

>>> greeter = Greeter()

>>> greeter.say_hello()
Hello, Pythonista

>>> Greeter.__dict__
mappingproxy({..., 'say_hello': , ...})
6 thay vì
>>> from greet import Greeter

>>> greeter = Greeter()

>>> greeter.say_hello()
Hello, Pythonista

>>> Greeter.__dict__
mappingproxy({..., 'say_hello': , ...})
7 trên màn hình của mình, điều này xác nhận rằng việc triển khai phương thức thứ hai chiếm ưu thế trong lần đầu tiên.

Dòng mã cuối cùng kiểm tra nội dung của

# greet.py

class Greeter:
    def say_hello(self):
        print("Hello, World")

    def say_hello(self):
        print("Hello, Pythonista")
9, phát hiện ra rằng tên phương thức,
>>> from greet import Greeter

>>> greeter = Greeter()

>>> greeter.say_hello()
Hello, Pythonista

>>> Greeter.__dict__
mappingproxy({..., 'say_hello': , ...})
9, chỉ xuất hiện một lần trong không gian tên lớp. Điều này phù hợp với cách từ điển hoạt động trong Python.

Một cái gì đó tương tự xảy ra với các chức năng trong mô -đun Python và trong một phiên tương tác. Việc triển khai cuối cùng của một số chức năng có cùng tên chiếm ưu thế trong phần còn lại của các triển khai:

>>>

>>> def say_hello():
...     print("Hello, World")
...

>>> def say_hello():
...     print("Hello, Pythonista")
...

>>> say_hello()
Hello Pythonista

Trong ví dụ này, bạn gọi

>>> from greet import Greeter

>>> greeter = Greeter()

>>> greeter.say_hello()
Hello, Pythonista

>>> Greeter.__dict__
mappingproxy({..., 'say_hello': , ...})
3 vào
>>> from greet import Greeter

>>> greeter = Greeter()

>>> greeter.say_hello()
Hello, Pythonista

>>> Greeter.__dict__
mappingproxy({..., 'say_hello': , ...})
4, đây là một ví dụ của lớp
>>> from greet import Greeter

>>> greeter = Greeter()

>>> greeter.say_hello()
Hello, Pythonista

>>> Greeter.__dict__
mappingproxy({..., 'say_hello': , ...})
1. Bạn nhận được
>>> from greet import Greeter

>>> greeter = Greeter()

>>> greeter.say_hello()
Hello, Pythonista

>>> Greeter.__dict__
mappingproxy({..., 'say_hello': , ...})
6 thay vì
>>> from greet import Greeter

>>> greeter = Greeter()

>>> greeter.say_hello()
Hello, Pythonista

>>> Greeter.__dict__
mappingproxy({..., 'say_hello': , ...})
7 trên màn hình của mình, điều này xác nhận rằng việc triển khai phương thức thứ hai chiếm ưu thế trong lần đầu tiên.

Dòng mã cuối cùng kiểm tra nội dung của

# greet.py

class Greeter:
    def say_hello(self):
        print("Hello, World")

    def say_hello(self):
        print("Hello, Pythonista")
9, phát hiện ra rằng tên phương thức,
>>> from greet import Greeter

>>> greeter = Greeter()

>>> greeter.say_hello()
Hello, Pythonista

>>> Greeter.__dict__
mappingproxy({..., 'say_hello': , ...})
9, chỉ xuất hiện một lần trong không gian tên lớp. Điều này phù hợp với cách từ điển hoạt động trong Python.

Một cái gì đó tương tự xảy ra với các chức năng trong mô -đun Python và trong một phiên tương tác. Việc triển khai cuối cùng của một số chức năng có cùng tên chiếm ưu thế trong phần còn lại của các triển khai:

Bạn xác định hai chức năng có cùng tên,

>>> def say_hello():
...     print("Hello, World")
...

>>> def say_hello():
...     print("Hello, Pythonista")
...

>>> say_hello()
Hello Pythonista
0, trong cùng một phiên phiên dịch. Tuy nhiên, định nghĩa thứ hai ghi đè lên định nghĩa thứ nhất. Khi bạn gọi hàm, bạn sẽ nhận được
>>> from greet import Greeter

>>> greeter = Greeter()

>>> greeter.say_hello()
Hello, Pythonista

>>> Greeter.__dict__
mappingproxy({..., 'say_hello': , ...})
6, điều này xác nhận rằng định nghĩa hàm cuối cùng chiếm ưu thế.

Một kỹ thuật khác mà một số ngôn ngữ lập trình sử dụng để cung cấp nhiều cách để gọi một phương thức hoặc hàm là nhiều công văn.

Với kỹ thuật này, bạn có thể viết một số triển khai khác nhau của cùng một phương thức hoặc chức năng và tự động gửi quá trình thực hiện mong muốn theo loại hoặc các đặc điểm khác của các đối số được sử dụng trong cuộc gọi. Bạn có thể sử dụng một vài công cụ từ thư viện tiêu chuẩn để kéo kỹ thuật này vào mã Python của bạn.

Python là một ngôn ngữ khá linh hoạt và giàu tính năng và cung cấp một vài cách để thực hiện nhiều hàm tạo và làm cho các lớp của bạn linh hoạt hơn.optional arguments using default argument values. This way, you can call the class constructor in different ways and get a different behavior each time.

Trong phần sau, bạn sẽ mô phỏng nhiều hàm tạo bằng cách truyền các đối số tùy chọn và bằng cách kiểm tra các loại đối số để xác định các hành vi khác nhau trong các bộ khởi tạo thể hiện của bạn.data type of the arguments to

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
4 to provide different behaviors depending on the concrete data type that you pass in the call. This technique allows you to simulate multiple constructors in a class.

Mô phỏng nhiều hàm tạo trong các lớp của bạn

Sử dụng các giá trị đối số tùy chọn trong >>> # Define a Person class >>> class Person: ... def __init__(self, name): ... self.name = name ... 4

Một cách thanh lịch và pythonic để mô phỏng nhiều hàm tạo là thực hiện phương pháp

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
4 với các đối số tùy chọn. Bạn có thể làm điều này bằng cách chỉ định các giá trị đối số mặc định phù hợp.optional arguments. You can do this by specifying appropriate default argument values.

Để kết thúc này, giả sử bạn cần mã hóa một lớp nhà máy được gọi là

>>> def say_hello():
...     print("Hello, World")
...

>>> def say_hello():
...     print("Hello, Pythonista")
...

>>> say_hello()
Hello Pythonista
8. Lớp này sẽ tạo các đối tượng có thể gọi được tính toán các quyền hạn cụ thể, sử dụng một luồng số làm đầu vào. Bạn cũng cần lớp của bạn để theo dõi tổng số tiền liên tiếp. Cuối cùng, lớp của bạn sẽ chấp nhận một đối số giữ một giá trị ban đầu cho tổng sức mạnh.

Hãy tiếp tục và tạo một tệp

>>> def say_hello():
...     print("Hello, World")
...

>>> def say_hello():
...     print("Hello, Pythonista")
...

>>> say_hello()
Hello Pythonista
9 trong thư mục hiện tại của bạn. Sau đó nhập mã sau để thực hiện
>>> def say_hello():
...     print("Hello, World")
...

>>> def say_hello():
...     print("Hello, Pythonista")
...

>>> say_hello()
Hello Pythonista
8:

# power.py

class CumulativePowerFactory:
    def __init__(self, exponent=2, *, start=0):
        self._exponent = exponent
        self.total = start

    def __call__(self, base):
        power = base ** self._exponent
        self.total += power
        return power

Bộ khởi tạo của

>>> def say_hello():
...     print("Hello, World")
...

>>> def say_hello():
...     print("Hello, Pythonista")
...

>>> say_hello()
Hello Pythonista
8 có hai đối số tùy chọn,
# power.py

class CumulativePowerFactory:
    def __init__(self, exponent=2, *, start=0):
        self._exponent = exponent
        self.total = start

    def __call__(self, base):
        power = base ** self._exponent
        self.total += power
        return power
2 và
# power.py

class CumulativePowerFactory:
    def __init__(self, exponent=2, *, start=0):
        self._exponent = exponent
        self.total = start

    def __call__(self, base):
        power = base ** self._exponent
        self.total += power
        return power
3. Đối số đầu tiên giữ số mũ mà bạn sẽ sử dụng để tính toán một loạt các quyền hạn. Nó mặc định là
# power.py

class CumulativePowerFactory:
    def __init__(self, exponent=2, *, start=0):
        self._exponent = exponent
        self.total = start

    def __call__(self, base):
        power = base ** self._exponent
        self.total += power
        return power
4, đây là một giá trị thường được sử dụng khi nói đến các quyền hạn tính toán.

Biểu tượng sao hoặc dấu hoa thị (

# power.py

class CumulativePowerFactory:
    def __init__(self, exponent=2, *, start=0):
        self._exponent = exponent
        self.total = start

    def __call__(self, base):
        power = base ** self._exponent
        self.total += power
        return power
5) sau
# power.py

class CumulativePowerFactory:
    def __init__(self, exponent=2, *, start=0):
        self._exponent = exponent
        self.total = start

    def __call__(self, base):
        power = base ** self._exponent
        self.total += power
        return power
2 có nghĩa là
# power.py

class CumulativePowerFactory:
    def __init__(self, exponent=2, *, start=0):
        self._exponent = exponent
        self.total = start

    def __call__(self, base):
        power = base ** self._exponent
        self.total += power
        return power
3 là một đối số chỉ dành cho từ khóa. Để chuyển một giá trị cho một đối số chỉ từ khóa, bạn cần sử dụng tên đối số một cách rõ ràng. Nói cách khác, để đặt
# power.py

class CumulativePowerFactory:
    def __init__(self, exponent=2, *, start=0):
        self._exponent = exponent
        self.total = start

    def __call__(self, base):
        power = base ** self._exponent
        self.total += power
        return power
8 thành
# power.py

class CumulativePowerFactory:
    def __init__(self, exponent=2, *, start=0):
        self._exponent = exponent
        self.total = start

    def __call__(self, base):
        power = base ** self._exponent
        self.total += power
        return power
9, bạn cần gõ rõ ràng
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
00.

Đối số

# power.py

class CumulativePowerFactory:
    def __init__(self, exponent=2, *, start=0):
        self._exponent = exponent
        self.total = start

    def __call__(self, base):
        power = base ** self._exponent
        self.total += power
        return power
3 giữ giá trị ban đầu để tính tổng công suất tích lũy. Nó mặc định là
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
02, là giá trị thích hợp cho những trường hợp mà bạn không có giá trị được tính toán trước đây để khởi tạo tổng công suất tích lũy.

Phương pháp đặc biệt

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
03 biến các phiên bản của
>>> def say_hello():
...     print("Hello, World")
...

>>> def say_hello():
...     print("Hello, Pythonista")
...

>>> say_hello()
Hello Pythonista
8 thành các đối tượng có thể gọi được. Nói cách khác, bạn có thể gọi các phiên bản của
>>> def say_hello():
...     print("Hello, World")
...

>>> def say_hello():
...     print("Hello, Pythonista")
...

>>> say_hello()
Hello Pythonista
8 như bạn gọi bất kỳ chức năng chính quy nào.callable objects. In other words, you can call the instances of
>>> def say_hello():
...     print("Hello, World")
...

>>> def say_hello():
...     print("Hello, Pythonista")
...

>>> say_hello()
Hello Pythonista
8 like you call any regular function.

Bên trong

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
03, trước tiên bạn tính toán sức mạnh của
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
07 được nâng lên
# power.py

class CumulativePowerFactory:
    def __init__(self, exponent=2, *, start=0):
        self._exponent = exponent
        self.total = start

    def __call__(self, base):
        power = base ** self._exponent
        self.total += power
        return power
2. Sau đó, bạn thêm giá trị kết quả vào giá trị hiện tại của
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
09. Cuối cùng, bạn trả lại sức mạnh được tính toán.

Để thử

>>> def say_hello():
...     print("Hello, World")
...

>>> def say_hello():
...     print("Hello, Pythonista")
...

>>> say_hello()
Hello Pythonista
8, hãy mở một phiên tương tác Python trong thư mục chứa
>>> def say_hello():
...     print("Hello, World")
...

>>> def say_hello():
...     print("Hello, Pythonista")
...

>>> say_hello()
Hello Pythonista
9 và chạy mã sau:

>>>

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
0

Những ví dụ này cho thấy cách

>>> def say_hello():
...     print("Hello, World")
...

>>> def say_hello():
...     print("Hello, Pythonista")
...

>>> say_hello()
Hello Pythonista
8 mô phỏng nhiều hàm tạo. Ví dụ, hàm tạo đầu tiên không có đối số. Nó cho phép bạn tạo các phiên bản lớp tính toán quyền hạn của
# power.py

class CumulativePowerFactory:
    def __init__(self, exponent=2, *, start=0):
        self._exponent = exponent
        self.total = start

    def __call__(self, base):
        power = base ** self._exponent
        self.total += power
        return power
4, đây là giá trị mặc định của đối số
# power.py

class CumulativePowerFactory:
    def __init__(self, exponent=2, *, start=0):
        self._exponent = exponent
        self.total = start

    def __call__(self, base):
        power = base ** self._exponent
        self.total += power
        return power
2. Thuộc tính thể hiện ____109 chứa tổng tích lũy của các quyền hạn được tính toán khi bạn đi.

Ví dụ thứ hai cho thấy một hàm tạo lấy

# power.py

class CumulativePowerFactory:
    def __init__(self, exponent=2, *, start=0):
        self._exponent = exponent
        self.total = start

    def __call__(self, base):
        power = base ** self._exponent
        self.total += power
        return power
2 làm đối số và trả về một thể hiện có thể gọi được tính toán các khối. Trong trường hợp này,
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
09 hoạt động giống như trong ví dụ đầu tiên.

Ví dụ thứ ba cho thấy cách

>>> def say_hello():
...     print("Hello, World")
...

>>> def say_hello():
...     print("Hello, Pythonista")
...

>>> say_hello()
Hello Pythonista
8 dường như có một hàm tạo khác cho phép bạn tạo các phiên bản bằng cách cung cấp các đối số
# power.py

class CumulativePowerFactory:
    def __init__(self, exponent=2, *, start=0):
        self._exponent = exponent
        self.total = start

    def __call__(self, base):
        power = base ** self._exponent
        self.total += power
        return power
2 và
# power.py

class CumulativePowerFactory:
    def __init__(self, exponent=2, *, start=0):
        self._exponent = exponent
        self.total = start

    def __call__(self, base):
        power = base ** self._exponent
        self.total += power
        return power
3. Bây giờ
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
09 bắt đầu với giá trị
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
22, khởi tạo tổng sức mạnh.

Sử dụng các đối số tùy chọn khi bạn thực hiện

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
4 trong các lớp của bạn là một kỹ thuật sạch và pythonic để tạo ra các lớp mô phỏng nhiều hàm tạo.

Kiểm tra các loại đối số trong >>> # Define a Person class >>> class Person: ... def __init__(self, name): ... self.name = name ... 4

Một cách tiếp cận khác để mô phỏng nhiều hàm tạo là viết một phương thức

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
4 hoạt động khác nhau tùy thuộc vào loại đối số. Để kiểm tra loại biến trong Python, bạn thường dựa vào hàm
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
26 tích hợp. Hàm này trả về
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
27 Nếu một đối tượng là một thể hiện của một lớp đã cho và
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
28 nếu không:

>>>

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
1

Những ví dụ này cho thấy cách

>>> def say_hello():
...     print("Hello, World")
...

>>> def say_hello():
...     print("Hello, Pythonista")
...

>>> say_hello()
Hello Pythonista
8 mô phỏng nhiều hàm tạo. Ví dụ, hàm tạo đầu tiên không có đối số. Nó cho phép bạn tạo các phiên bản lớp tính toán quyền hạn của
# power.py

class CumulativePowerFactory:
    def __init__(self, exponent=2, *, start=0):
        self._exponent = exponent
        self.total = start

    def __call__(self, base):
        power = base ** self._exponent
        self.total += power
        return power
4, đây là giá trị mặc định của đối số
# power.py

class CumulativePowerFactory:
    def __init__(self, exponent=2, *, start=0):
        self._exponent = exponent
        self.total = start

    def __call__(self, base):
        power = base ** self._exponent
        self.total += power
        return power
2. Thuộc tính thể hiện ____109 chứa tổng tích lũy của các quyền hạn được tính toán khi bạn đi.

Ví dụ thứ hai cho thấy một hàm tạo lấy

# power.py

class CumulativePowerFactory:
    def __init__(self, exponent=2, *, start=0):
        self._exponent = exponent
        self.total = start

    def __call__(self, base):
        power = base ** self._exponent
        self.total += power
        return power
2 làm đối số và trả về một thể hiện có thể gọi được tính toán các khối. Trong trường hợp này,
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
09 hoạt động giống như trong ví dụ đầu tiên.

>>>

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
2

Những ví dụ này cho thấy cách

>>> def say_hello():
...     print("Hello, World")
...

>>> def say_hello():
...     print("Hello, Pythonista")
...

>>> say_hello()
Hello Pythonista
8 mô phỏng nhiều hàm tạo. Ví dụ, hàm tạo đầu tiên không có đối số. Nó cho phép bạn tạo các phiên bản lớp tính toán quyền hạn của
# power.py

class CumulativePowerFactory:
    def __init__(self, exponent=2, *, start=0):
        self._exponent = exponent
        self.total = start

    def __call__(self, base):
        power = base ** self._exponent
        self.total += power
        return power
4, đây là giá trị mặc định của đối số
# power.py

class CumulativePowerFactory:
    def __init__(self, exponent=2, *, start=0):
        self._exponent = exponent
        self.total = start

    def __call__(self, base):
        power = base ** self._exponent
        self.total += power
        return power
2. Thuộc tính thể hiện ____109 chứa tổng tích lũy của các quyền hạn được tính toán khi bạn đi.

Ví dụ thứ hai cho thấy một hàm tạo lấy

# power.py

class CumulativePowerFactory:
    def __init__(self, exponent=2, *, start=0):
        self._exponent = exponent
        self.total = start

    def __call__(self, base):
        power = base ** self._exponent
        self.total += power
        return power
2 làm đối số và trả về một thể hiện có thể gọi được tính toán các khối. Trong trường hợp này,
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
09 hoạt động giống như trong ví dụ đầu tiên.

Đó là nó! Bây giờ bạn có một phương thức

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
4 mô phỏng một lớp có nhiều hàm tạo. Một hàm tạo có đối số thuộc loại
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
32. Trình xây dựng khác lấy các đối số của loại chuỗi.

Kỹ thuật trong ví dụ trên có nhược điểm là nó không quy mô tốt. Nếu bạn có nhiều đối số có thể lấy giá trị của các loại dữ liệu khác nhau, thì việc triển khai của bạn có thể sớm trở thành một cơn ác mộng. Vì vậy, kỹ thuật này được coi là một mô hình chống trong Python.

Ví dụ: điều gì sẽ xảy ra nếu người dùng của bạn nhập giá trị thời gian UNIX cho

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
39? Kiểm tra đoạn mã sau:

>>>

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
3

Khi bạn truy cập

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
37, bạn sẽ nhận được một
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
48 vì câu lệnh có điều kiện của bạn không có một nhánh xem xét định dạng ngày khác.

Để khắc phục sự cố này, bạn có thể tiếp tục thêm các điều khoản

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
38 để bao gồm tất cả các định dạng ngày có thể mà người dùng có thể vượt qua. Bạn cũng có thể thêm một mệnh đề
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
50 để bắt các định dạng ngày không được hỗ trợ:unsupported date formats:

>>>

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
4

Khi bạn truy cập

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
37, bạn sẽ nhận được một
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
48 vì câu lệnh có điều kiện của bạn không có một nhánh xem xét định dạng ngày khác.

Để khắc phục sự cố này, bạn có thể tiếp tục thêm các điều khoản class CashDividends(KwargAttrs): def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency): # save the namespace before it gets polluted super().__init__(**locals()) # work that might pollute local namespace goes here # OPTIONAL: update the argument values in case they were modified: super()._update(**locals()) 38 để bao gồm tất cả các định dạng ngày có thể mà người dùng có thể vượt qua. Bạn cũng có thể thêm một mệnh đề class CashDividends(KwargAttrs): def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency): # save the namespace before it gets polluted super().__init__(**locals()) # work that might pollute local namespace goes here # OPTIONAL: update the argument values in case they were modified: super()._update(**locals()) 50 để bắt các định dạng ngày không được hỗ trợ:

Trong ví dụ này, mệnh đề

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
50 chạy nếu giá trị của
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
39 không phải là đối tượng
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
32 hoặc một chuỗi giữ một ngày ISO hợp lệ. Bằng cách này, tình huống đặc biệt không vượt qua âm thầm.class method.

Cung cấp nhiều hàm tạo với

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
0 trong Python

Một kỹ thuật mạnh mẽ để cung cấp nhiều hàm tạo trong Python là sử dụng

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
0. Bộ trang trí này cho phép bạn biến một phương pháp thông thường thành phương pháp lớp.

>>>

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
5

Khi bạn truy cập

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
37, bạn sẽ nhận được một
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
48 vì câu lệnh có điều kiện của bạn không có một nhánh xem xét định dạng ngày khác.

Để khắc phục sự cố này, bạn có thể tiếp tục thêm các điều khoản

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
38 để bao gồm tất cả các định dạng ngày có thể mà người dùng có thể vượt qua. Bạn cũng có thể thêm một mệnh đề
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
50 để bắt các định dạng ngày không được hỗ trợ:

Trong ví dụ này, mệnh đề

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
50 chạy nếu giá trị của
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
39 không phải là đối tượng
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
32 hoặc một chuỗi giữ một ngày ISO hợp lệ. Bằng cách này, tình huống đặc biệt không vượt qua âm thầm.alternative constructor in Python, as Raymond Hettinger does in his PyCon talk Python’s Class Development Toolkit.

Cung cấp nhiều hàm tạo với

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
0 trong Python

Một kỹ thuật mạnh mẽ để cung cấp nhiều hàm tạo trong Python là sử dụng >>> # Define a Person class >>> class Person: ... def __init__(self, name): ... self.name = name ... 0. Bộ trang trí này cho phép bạn biến một phương pháp thông thường thành phương pháp lớp.

Không giống như các phương pháp thông thường, các phương thức lớp don don lấy ví dụ hiện tại,

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
7, như một đối số. Thay vào đó, họ tự mình tham gia lớp học, thường được thông qua như đối số
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
57. Sử dụng
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
57 để đặt tên cho đối số này là một quy ước phổ biến trong cộng đồng Python.

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
6

Ở đây, cú pháp cơ bản để xác định phương pháp lớp:string representation for your class.

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
59 Xác định một phương pháp lớp sử dụng trình trang trí
>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
0 tích hợp Python. Đối số đầu tiên của
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
61 giữ bản thân lớp. Thông qua lập luận này, bạn có thể truy cập lớp từ bên trong chính nó. Trong ví dụ này, bạn truy cập thuộc tính
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
62, lưu trữ tên của lớp bên dưới dưới dạng chuỗi.

>>>

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
7

Khi bạn truy cập

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
37, bạn sẽ nhận được một
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
48 vì câu lệnh có điều kiện của bạn không có một nhánh xem xét định dạng ngày khác.

Để khắc phục sự cố này, bạn có thể tiếp tục thêm các điều khoản

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
38 để bao gồm tất cả các định dạng ngày có thể mà người dùng có thể vượt qua. Bạn cũng có thể thêm một mệnh đề
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
50 để bắt các định dạng ngày không được hỗ trợ:

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
8

Trong ví dụ này, mệnh đề

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
50 chạy nếu giá trị của
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
39 không phải là đối tượng
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
32 hoặc một chuỗi giữ một ngày ISO hợp lệ. Bằng cách này, tình huống đặc biệt không vượt qua âm thầm.

Cung cấp nhiều hàm tạo với

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
0 trong Python

Một kỹ thuật mạnh mẽ để cung cấp nhiều hàm tạo trong Python là sử dụng

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
0. Bộ trang trí này cho phép bạn biến một phương pháp thông thường thành phương pháp lớp.

Cuộc gọi đến đối số

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
57 tự động chạy các bước tạo và khởi tạo đối tượng mà Python cần để khởi tạo một lớp. Cuối cùng,
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
79 trả về thể hiện mới cho người gọi.

Tại đây, cách bạn có thể sử dụng hàm tạo hoàn toàn mới của mình để tạo vòng tròn bằng cách sử dụng đường kính:

>>>

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
9

Cuộc gọi đến

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
79 trên
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
68 trả về một thể hiện mới của lớp. Để xây dựng thể hiện đó, phương thức sử dụng đường kính thay vì bán kính. Lưu ý rằng phần còn lại của chức năng của
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
68 hoạt động giống như trước đây.

Sử dụng

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
0 như bạn đã làm trong ví dụ trên là cách phổ biến nhất để cung cấp nhiều hàm tạo rõ ràng trong các lớp của bạn. Với kỹ thuật này, bạn có tùy chọn để chọn đúng tên cho từng hàm tạo thay thế mà bạn cung cấp, có thể làm cho mã của bạn dễ đọc và duy trì hơn.

Xây dựng điểm cực từ tọa độ Cartesian

Để biết một ví dụ phức tạp hơn về việc cung cấp nhiều hàm tạo bằng các phương thức lớp, giả sử bạn có một lớp đại diện cho một điểm cực trong một ứng dụng liên quan đến toán học. Bạn cần một cách để làm cho lớp học của bạn linh hoạt hơn để bạn có thể xây dựng các trường hợp mới bằng các tọa độ Cartesian.

Tại đây, cách bạn có thể viết một hàm tạo để đáp ứng yêu cầu này:

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
0

Trong ví dụ này,

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
92 có hai đối số đại diện cho một điểm nhất định ____ ____193 và
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
94 tọa độ Cartesian. Sau đó, phương pháp tính toán yêu cầu
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
95 và
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
96 để xây dựng đối tượng
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
97 tương ứng. Cuối cùng,
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
92 trả về một thể hiện mới của lớp.

Ở đây, cách thức hoạt động của lớp, sử dụng cả hai hệ tọa độ:

>>>

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
1

Cuộc gọi đến

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
79 trên
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
68 trả về một thể hiện mới của lớp. Để xây dựng thể hiện đó, phương thức sử dụng đường kính thay vì bán kính. Lưu ý rằng phần còn lại của chức năng của
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
68 hoạt động giống như trước đây.

Sử dụng >>> # Define a Person class >>> class Person: ... def __init__(self, name): ... self.name = name ... 0 như bạn đã làm trong ví dụ trên là cách phổ biến nhất để cung cấp nhiều hàm tạo rõ ràng trong các lớp của bạn. Với kỹ thuật này, bạn có tùy chọn để chọn đúng tên cho từng hàm tạo thay thế mà bạn cung cấp, có thể làm cho mã của bạn dễ đọc và duy trì hơn.

Xây dựng điểm cực từ tọa độ Cartesian

Để biết một ví dụ phức tạp hơn về việc cung cấp nhiều hàm tạo bằng các phương thức lớp, giả sử bạn có một lớp đại diện cho một điểm cực trong một ứng dụng liên quan đến toán học. Bạn cần một cách để làm cho lớp học của bạn linh hoạt hơn để bạn có thể xây dựng các trường hợp mới bằng các tọa độ Cartesian.

Tại đây, cách bạn có thể viết một hàm tạo để đáp ứng yêu cầu này:

Trong ví dụ này,

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
92 có hai đối số đại diện cho một điểm nhất định ____ ____193 và
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
94 tọa độ Cartesian. Sau đó, phương pháp tính toán yêu cầu
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
95 và
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
96 để xây dựng đối tượng
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
97 tương ứng. Cuối cùng,
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
92 trả về một thể hiện mới của lớp.

Ở đây, cách thức hoạt động của lớp, sử dụng cả hai hệ tọa độ:

Trong các ví dụ này, bạn sử dụng quy trình khởi tạo tiêu chuẩn và hàm tạo thay thế của bạn,

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
92, để tạo các trường hợp
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
97 bằng cách sử dụng các đối số khởi tạo khác nhau về mặt khái niệm.

Khám phá nhiều hàm tạo trong các lớp Python hiện có

Sử dụng trình trang trí

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
0 để cung cấp nhiều hàm tạo trong một lớp là một kỹ thuật khá phổ biến trong Python. Có một số ví dụ về các lớp thư viện tiêu chuẩn và tích hợp sử dụng kỹ thuật này để cung cấp nhiều hàm tạo thay thế.

>>>

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
2

Cuộc gọi đến

class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
79 trên
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
68 trả về một thể hiện mới của lớp. Để xây dựng thể hiện đó, phương thức sử dụng đường kính thay vì bán kính. Lưu ý rằng phần còn lại của chức năng của
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
68 hoạt động giống như trước đây.

Sử dụng

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
0 như bạn đã làm trong ví dụ trên là cách phổ biến nhất để cung cấp nhiều hàm tạo rõ ràng trong các lớp của bạn. Với kỹ thuật này, bạn có tùy chọn để chọn đúng tên cho từng hàm tạo thay thế mà bạn cung cấp, có thể làm cho mã của bạn dễ đọc và duy trì hơn.

Xây dựng điểm cực từ tọa độ Cartesian

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
3

Để biết một ví dụ phức tạp hơn về việc cung cấp nhiều hàm tạo bằng các phương thức lớp, giả sử bạn có một lớp đại diện cho một điểm cực trong một ứng dụng liên quan đến toán học. Bạn cần một cách để làm cho lớp học của bạn linh hoạt hơn để bạn có thể xây dựng các trường hợp mới bằng các tọa độ Cartesian.

Tạo đối tượng class StockSplits(KwargAttrs): def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency): super().__init__(**locals()) 03

Lớp

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
03 từ thư viện tiêu chuẩn là một lớp khác tận dụng nhiều hàm tạo. Lớp này cung cấp một số hàm tạo thay thế, chẳng hạn như
class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
35,
class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
36,
class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
37 và
class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
38. Tất cả chúng cho phép bạn xây dựng các đối tượng
class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
03 bằng cách sử dụng các đối số khác nhau về mặt khái niệm.

Dưới đây là một vài ví dụ về cách sử dụng một số hàm tạo đó để tạo các đối tượng

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
03:

>>>

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
4

Ví dụ đầu tiên sử dụng hàm tạo lớp tiêu chuẩn làm tài liệu tham khảo. Ví dụ thứ hai cho thấy cách bạn có thể sử dụng

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
35 để xây dựng đối tượng
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
32 từ ngày hiện tại.

Phần còn lại của các ví dụ cho thấy cách

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
03 sử dụng một số phương thức lớp để cung cấp nhiều hàm tạo. Sự đa dạng của các hàm tạo này làm cho quá trình khởi tạo khá linh hoạt và mạnh mẽ, bao gồm một loạt các trường hợp sử dụng. Nó cũng cải thiện khả năng đọc mã của bạn với tên phương thức mô tả.

Tìm con đường của bạn về nhà

Mô -đun Python từ

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
44 từ thư viện tiêu chuẩn cung cấp các công cụ tiện lợi và hiện đại để xử lý các đường dẫn hệ thống trong mã của bạn. Nếu bạn không bao giờ sử dụng mô -đun này, thì hãy xem mô -đun Python 3 Pathlib: Tâm hệ thống tệp.

Công cụ đẹp nhất trong

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
44 là lớp
class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
46 của nó. Lớp này cho phép bạn xử lý đường dẫn hệ thống của mình theo cách đa nền tảng.
class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
46 là một lớp thư viện tiêu chuẩn khác cung cấp nhiều hàm tạo. Ví dụ: bạn sẽ tìm thấy
class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
48, tạo ra một đối tượng đường dẫn từ thư mục nhà của bạn:

  • các cửa sổ
  • Linux + MacOS

>>>

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
5

>>>

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
6

Ví dụ đầu tiên sử dụng hàm tạo lớp tiêu chuẩn làm tài liệu tham khảo. Ví dụ thứ hai cho thấy cách bạn có thể sử dụng

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
35 để xây dựng đối tượng
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
32 từ ngày hiện tại.

Phần còn lại của các ví dụ cho thấy cách

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
03 sử dụng một số phương thức lớp để cung cấp nhiều hàm tạo. Sự đa dạng của các hàm tạo này làm cho quá trình khởi tạo khá linh hoạt và mạnh mẽ, bao gồm một loạt các trường hợp sử dụng. Nó cũng cải thiện khả năng đọc mã của bạn với tên phương thức mô tả.

Tìm con đường của bạn về nhà

Mô -đun Python từ

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
44 từ thư viện tiêu chuẩn cung cấp các công cụ tiện lợi và hiện đại để xử lý các đường dẫn hệ thống trong mã của bạn. Nếu bạn không bao giờ sử dụng mô -đun này, thì hãy xem mô -đun Python 3 Pathlib: Tâm hệ thống tệp.

Công cụ đẹp nhất trong

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
44 là lớp
class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
46 của nó. Lớp này cho phép bạn xử lý đường dẫn hệ thống của mình theo cách đa nền tảng.
class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
46 là một lớp thư viện tiêu chuẩn khác cung cấp nhiều hàm tạo. Ví dụ: bạn sẽ tìm thấy
class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
48, tạo ra một đối tượng đường dẫn từ thư mục nhà của bạn:dispatch algorithm determines which implementation to run based on the type of a single argument. That’s where the term single dispatch comes from.

các cửa sổ

Linux + MacOS

Trình xây dựng class StockSplits(KwargAttrs): def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency): super().__init__(**locals()) 49 trả về một đối tượng đường dẫn mới đại diện cho thư mục nhà của người dùng. Trình xây dựng thay thế này có thể hữu ích khi bạn xử lý các tệp cấu hình trong các ứng dụng và dự án Python của bạn.

Cuối cùng,

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
46 cũng cung cấp một hàm tạo gọi là
class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
51. Phương pháp này tạo ra một đối tượng đường dẫn từ thư mục làm việc hiện tại của bạn. Hãy tiếp tục và thử nó!

Cung cấp nhiều hàm tạo với

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
1

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
7

Kỹ thuật cuối cùng mà bạn sẽ học được được gọi là các hàm chung đơn. Với kỹ thuật này, bạn có thể thêm nhiều hàm tạo vào các lớp của mình và chạy chúng một cách chọn lọc, theo loại đối số đầu tiên của họ.

Chức năng chung chung đơn bao gồm nhiều chức năng thực hiện cùng một hoạt động cho các loại dữ liệu khác nhau. Thuật toán công văn cơ bản xác định việc thực hiện để chạy dựa trên loại đối số duy nhất. Đó là nơi mà thuật ngữ một công văn xuất phát.non-public and prevent direct calls from your end users.

Bắt đầu với Python 3.8, bạn có thể sử dụng trình trang trí

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
53 hoặc
>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
1 để biến hàm hoặc phương thức, tương ứng, thành một hàm chung đơn. PEP 443 giải thích rằng bạn có thể tìm thấy các nhà trang trí này trong mô -đun
class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
55.

Trong một chức năng thông thường, Python chọn cách thực hiện để gửi theo loại đối số đầu tiên của hàm. Trong một phương thức, đối số đích là định hướng đầu tiên ngay sau

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
7.

>>>

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
8

Ví dụ đầu tiên sử dụng hàm tạo lớp tiêu chuẩn làm tài liệu tham khảo. Ví dụ thứ hai cho thấy cách bạn có thể sử dụng

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
35 để xây dựng đối tượng
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
32 từ ngày hiện tại.

Bạn cũng có thể sử dụng kỹ thuật này để quá tải

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
4, cho phép bạn cung cấp nhiều triển khai cho phương pháp này, và do đó, lớp của bạn sẽ có nhiều hàm tạo.

Một ví dụ trong thế giới thực về phương pháp đơn lẻ

Như một ví dụ thực tế hơn về việc sử dụng

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
1, giả sử bạn cần tiếp tục thêm các tính năng vào lớp
>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
5 của mình. Lần này, bạn cần cung cấp một cách để tính toán tuổi gần đúng của một người dựa trên ngày sinh của họ. Để thêm tính năng này vào
>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
5, bạn có thể sử dụng một lớp trợ giúp xử lý tất cả các thông tin liên quan đến ngày sinh và tuổi.

Hãy tiếp tục và tạo một tệp có tên

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
75 trong thư mục làm việc của bạn. Sau đó thêm mã sau vào nó:

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
9

Ở đây, một sự cố về cách thức hoạt động của mã này:

  • Dòng 3 nhập

    class CashDividends(KwargAttrs):
        def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
            # save the namespace before it gets polluted
            super().__init__(**locals()) 
    
            # work that might pollute local namespace goes here
    
            # OPTIONAL: update the argument values in case they were modified: 
            super()._update(**locals())
    
    32 từ
    class StockSplits(KwargAttrs):
        def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
            super().__init__(**locals())
    
    77 để sau này bạn có thể chuyển đổi bất kỳ ngày đầu vào nào thành đối tượng
    class CashDividends(KwargAttrs):
        def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
            # save the namespace before it gets polluted
            super().__init__(**locals()) 
    
            # work that might pollute local namespace goes here
    
            # OPTIONAL: update the argument values in case they were modified: 
            super()._update(**locals())
    
    32.
    imports
    class CashDividends(KwargAttrs):
        def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
            # save the namespace before it gets polluted
            super().__init__(**locals()) 
    
            # work that might pollute local namespace goes here
    
            # OPTIONAL: update the argument values in case they were modified: 
            super()._update(**locals())
    
    32 from
    class StockSplits(KwargAttrs):
        def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
            super().__init__(**locals())
    
    77 so that you can later convert any input date to a
    class CashDividends(KwargAttrs):
        def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
            # save the namespace before it gets polluted
            super().__init__(**locals()) 
    
            # work that might pollute local namespace goes here
    
            # OPTIONAL: update the argument values in case they were modified: 
            super()._update(**locals())
    
    32 object.

  • Dòng 4 nhập

    >>> # Define a Person class
    >>> class Person:
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    
    1 để xác định phương thức quá tải. imports
    >>> # Define a Person class
    >>> class Person:
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    
    1 to define the overloaded method.

  • Dòng 6 định nghĩa

    class StockSplits(KwargAttrs):
        def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
            super().__init__(**locals())
    
    80 là một lớp Python thông thường. defines
    class StockSplits(KwargAttrs):
        def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
            super().__init__(**locals())
    
    80 as a regular Python class.

  • Các dòng 7 đến 9 Xác định trình khởi tạo lớp là phương thức chung đơn lẻ bằng cách sử dụng

    >>> # Define a Person class
    >>> class Person:
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    
    1. Đây là phương pháp triển khai cơ sở và nó tăng
    class StockSplits(KwargAttrs):
        def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
            super().__init__(**locals())
    
    82 cho các định dạng ngày không được hỗ trợ.
    define the class initializer as a single-dispatch generic method using
    >>> # Define a Person class
    >>> class Person:
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    
    1. This is the method’s base implementation, and it raises a
    class StockSplits(KwargAttrs):
        def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
            super().__init__(**locals())
    
    82 for unsupported date formats.

  • Các dòng 11 đến 13 Đăng ký triển khai

    >>> # Define a Person class
    >>> class Person:
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    
    4 xử lý trực tiếp các đối tượng
    class CashDividends(KwargAttrs):
        def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
            # save the namespace before it gets polluted
            super().__init__(**locals()) 
    
            # work that might pollute local namespace goes here
    
            # OPTIONAL: update the argument values in case they were modified: 
            super()._update(**locals())
    
    32.
    register an implementation of
    >>> # Define a Person class
    >>> class Person:
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    
    4 that processes
    class CashDividends(KwargAttrs):
        def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
            # save the namespace before it gets polluted
            super().__init__(**locals()) 
    
            # work that might pollute local namespace goes here
    
            # OPTIONAL: update the argument values in case they were modified: 
            super()._update(**locals())
    
    32 objects directly.

  • Các dòng 15 đến 17 Xác định việc thực hiện

    >>> # Define a Person class
    >>> class Person:
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    
    4 mà các ngày xử lý các ngày đến như các chuỗi có định dạng ISO. define the implementation of
    >>> # Define a Person class
    >>> class Person:
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    
    4 that processes dates that come as strings with an ISO format.

  • Các dòng 19 đến 22 Đăng ký một triển khai xử lý ngày diễn ra theo thời gian Unix tính bằng giây kể từ thời đại. Lần này, bạn đăng ký hai trường hợp của phương thức quá tải bằng cách xếp loại trang trí

    class StockSplits(KwargAttrs):
        def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
            super().__init__(**locals())
    
    58 với các loại
    class StockSplits(KwargAttrs):
        def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
            super().__init__(**locals())
    
    69 và
    class StockSplits(KwargAttrs):
        def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
            super().__init__(**locals())
    
    88.
    register an implementation that processes dates that come as Unix time in seconds since the epoch. This time, you register two instances of the overloaded method by stacking the
    class StockSplits(KwargAttrs):
        def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
            super().__init__(**locals())
    
    58 decorator with the
    class StockSplits(KwargAttrs):
        def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
            super().__init__(**locals())
    
    69 and
    class StockSplits(KwargAttrs):
        def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
            super().__init__(**locals())
    
    88 types.

  • Các dòng 24 đến 25 cung cấp một phương pháp thường xuyên để tính toán tuổi của một người nhất định. Lưu ý rằng việc thực hiện

    class StockSplits(KwargAttrs):
        def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
            super().__init__(**locals())
    
    89 là hoàn toàn chính xác vì nó không xem xét tháng và ngày trong năm khi tính độ tuổi. Phương pháp
    class StockSplits(KwargAttrs):
        def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
            super().__init__(**locals())
    
    89 chỉ là một tính năng thưởng để làm phong phú ví dụ.
    provide a regular method to compute the age of a given person. Note that the implementation of
    class StockSplits(KwargAttrs):
        def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
            super().__init__(**locals())
    
    89 isn’t totally accurate because it doesn’t consider the month and day of the year when calculating the age. The
    class StockSplits(KwargAttrs):
        def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
            super().__init__(**locals())
    
    89 method is just a bonus feature to enrich the example.

Bây giờ bạn có thể sử dụng thành phần trong lớp

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
5 của mình để tận dụng lớp
class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
80 mới. Đi trước và cập nhật
>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
5 với mã sau:

class CorporateActions(KwargAttrs):
    def __init__(self, stock_splits , cash_dividends):
        super().__init__(**locals())

ca = CorporateActions(stock_splits = StockSplits(), cash_dividends = CashDividends() )
0

Trong bản cập nhật này,

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
5 có một thuộc tính không công khai mới có tên là
class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
95, đây là một ví dụ là
class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
80. Trường hợp này được khởi tạo với đối số đầu vào
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
39. Bộ khởi tạo quá tải của
class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
80 sẽ khởi tạo
class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
95 theo ngày sinh của người dùng.

Sau đó, bạn xác định

class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
89 là một thuộc tính để cung cấp một thuộc tính được tính toán trả về độ tuổi gần đúng của người. Việc bổ sung cuối cùng cho
>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
5 là thuộc tính
class CorporateActions(KwargAttrs):
    def __init__(self, stock_splits , cash_dividends):
        super().__init__(**locals())

ca = CorporateActions(stock_splits = StockSplits(), cash_dividends = CashDividends() )
02, trả lại ngày sinh của người đó dưới dạng đối tượng
class CashDividends(KwargAttrs):
    def __init__(self, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        # save the namespace before it gets polluted
        super().__init__(**locals()) 

        # work that might pollute local namespace goes here

        # OPTIONAL: update the argument values in case they were modified: 
        super()._update(**locals())
32.

Để thử các lớp

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
5 và
class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
80 của bạn, hãy mở một phiên tương tác và chạy mã sau:

>>>

class CorporateActions(KwargAttrs):
    def __init__(self, stock_splits , cash_dividends):
        super().__init__(**locals())

ca = CorporateActions(stock_splits = StockSplits(), cash_dividends = CashDividends() )
1

Bạn có thể khởi tạo

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
5 bằng các định dạng ngày khác nhau. Thể hiện nội bộ của
class CorporateActions(KwargAttrs):
    def __init__(self, stock_splits , cash_dividends):
        super().__init__(**locals())

ca = CorporateActions(stock_splits = StockSplits(), cash_dividends = CashDividends() )
07 tự động chuyển đổi ngày đầu vào thành một đối tượng ngày. Nếu bạn khởi tạo
>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
5 với định dạng ngày không được hỗ trợ, chẳng hạn như từ điển, thì bạn sẽ nhận được
class StockSplits(KwargAttrs):
    def __init__(self, stocksplitratio, gross, net, ISIN, paydate, exdate, recorddate, frequency, type, announceddate, currency):
        super().__init__(**locals())
82.

Lưu ý rằng

class CorporateActions(KwargAttrs):
    def __init__(self, stock_splits , cash_dividends):
        super().__init__(**locals())

ca = CorporateActions(stock_splits = StockSplits(), cash_dividends = CashDividends() )
10 chăm sóc xử lý ngày sinh đầu vào cho bạn. Không cần phải sử dụng các hàm tạo thay thế rõ ràng để xử lý các loại đầu vào khác nhau. Bạn chỉ có thể khởi tạo lớp bằng hàm tạo tiêu chuẩn.

Hạn chế chính của kỹ thuật phương pháp đơn lẻ là nó dựa vào một đối số duy nhất, đối số đầu tiên sau

>>> # Define a Person class
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
7. Nếu bạn cần sử dụng nhiều đối số để gửi các triển khai phù hợp, thì hãy kiểm tra một số thư viện của bên thứ ba hiện có, chẳng hạn như MultipleSpatch và Multimethod.

Sự kết luận

Viết các lớp Python với nhiều hàm tạo có thể làm cho mã của bạn linh hoạt và linh hoạt hơn, bao gồm một loạt các trường hợp sử dụng. Nhiều hàm tạo là một tính năng mạnh mẽ cho phép bạn xây dựng các phiên bản của lớp cơ bản bằng cách sử dụng các đối số của các loại khác nhau, một số lượng đối số khác nhau hoặc cả hai, tùy thuộc vào nhu cầu của bạn.multiple constructors can make your code more versatile and flexible, covering a wide range of use cases. Multiple constructors are a powerful feature that allows you to build instances of the underlying class using arguments of different types, a different number of arguments, or both, depending on your needs.

Trong hướng dẫn này, bạn đã học được cách:

  • Mô phỏng nhiều hàm tạo bằng cách sử dụng các đối số tùy chọn và kiểm tra loạioptional arguments and type checking
  • Viết nhiều hàm tạo bằng cách sử dụng trình trang trí
    >>> # Define a Person class
    >>> class Person:
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    
    0 tích hợp
    >>> # Define a Person class
    >>> class Person:
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    
    0
    decorator
  • Quá tải các hàm tạo lớp của bạn bằng cách sử dụng trình trang trí
    >>> # Define a Person class
    >>> class Person:
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    
    1
    >>> # Define a Person class
    >>> class Person:
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    
    1
    decorator

Bạn cũng đã học được cách Python xây dựng các trường hợp của một lớp nhất định và cách một số lớp thư viện tiêu chuẩn cung cấp nhiều hàm tạo.constructs instances of a given class and how some standard-library classes provide multiple constructors.

Với kiến ​​thức này, bây giờ bạn có thể thêm gia vị cho các lớp học của mình với nhiều nhà xây dựng, trang bị cho họ một số cách để giải quyết quá trình khởi tạo trong Python.

Chúng ta có thể tạo nhiều lớp trong Python không?

Trong Python, có một số kỹ thuật và công cụ mà bạn có thể sử dụng để xây dựng các lớp, bao gồm mô phỏng nhiều hàm tạo thông qua các đối số tùy chọn, tùy chỉnh tạo thể hiện thông qua các phương thức lớp và thực hiện công văn đặc biệt với các trình trang trí.simulating multiple constructors through optional arguments, customizing instance creation via class methods, and doing special dispatch with decorators.

Bạn có thể tạo nhiều lớp trong một tệp Python không?

Vì vậy, tùy thuộc vào kịch bản và tiện lợi người ta có thể có một hoặc nhiều lớp cho mỗi tệp trong Python.one can have one or more classes per file in Python.

Làm thế nào để bạn sử dụng nhiều lớp trong Python?

Một lớp có thể được lấy từ nhiều lớp cơ sở trong Python, tương tự như C ++.Điều này được gọi là nhiều kế thừa.Trong nhiều kế thừa, các tính năng của tất cả các lớp cơ sở được kế thừa vào lớp dẫn xuất.Cú pháp cho nhiều kế thừa tương tự như thừa kế đơn.. This is called multiple inheritance. In multiple inheritance, the features of all the base classes are inherited into the derived class. The syntax for multiple inheritance is similar to single inheritance.

Bạn có thể có nhiều __ init __ python?

Có một số cách mà một phương thức __init__ có thể được gọi là nhiều lần.Có thể có nhiều hơn một cuộc gọi rõ ràng đến phương thức trong hệ thống phân cấp của các phương thức __init__.Một lớp sử dụng nhiều kế thừa trực tiếp gọi các phương thức __init__ của các loại cơ sở của nó.. There may be more than one explicit call to the method in the hierarchy of __init__ methods. A class using multiple inheritance directly calls the __init__ methods of its base types.