高級Python:定義類時要應用的9種最佳做法

重點 (Top highlight)

At its core, Python is an object-oriented programming (OOP) language. Being an OOP language, Python handles data and functionalities by supporting various features centered around objects. For instance, data structures are all objects, including primitive types (e.g., integers and strings) which aren’t considered objects in some other languages. For another instance, functions are all objects, and they are merely attributes of other objects where they are defined (e.g., class or module).

Python的核心是一種面向對象的編程(OOP)語言。 作為一種OOP語言,Python通過支持圍繞對象的各種功能來處理數據和功能。 例如,數據結構是所有對象,包括原始類型(例如,整數和字符串),在某些其他語言中這些原始類型不被視為對象。 對于另一個實例,函數是所有對象,它們僅僅是定義了它們的其他對象(例如,類或模塊)的屬性。

Although you can use built-in data types and write a bunch of functions without creating any custom classes, chances are that your code can become harder and harder to maintain when the project’s scope grows. These separate pieces have no shared themes, and there will be lots of hassles to manage connections between them, although much of the information is related.

盡管您可以使用內置數據類型并編寫許多函數而無需創建任何自定義類,但是隨著項目范圍的擴大,您的代碼可能會變得越來越難維護。 這些單獨的部分沒有共享的主題,并且盡管有很多信息是相關的,但要管理它們之間的連接仍會有很多麻煩。

In these scenarios, it’s worth defining your own classes, which will allow you to group related information and improve the structural design of your project. More importantly, the long-term maintainability of your codebase will be improved, because you’ll be dealing with less pieced code. However, there is a catch — this is only true when your class declaration is done in the right way such that the benefits of defining custom classes can outweigh the overhead of managing them.

在這些情況下,定義自己的類是值得的,這將使您可以對相關信息進行分組并改善項目的結構設計。 更重要的是,代碼庫的長期可維護性將得到改善,因為您將處理更少的分段代碼。 但是,有一個陷阱-僅當您以正確的方式完成類聲明時才如此,以至于定義自定義類的好處可能超過管理它們的開銷。

In this article, I’d like to review nine important best practices that you should consider applying to your custom classes.

在本文中,我想回顧九種重要的最佳實踐,您應該考慮將其應用于自定義類。

1.好名聲 (1. Good Names)

When you’re defining your own class, you’re adding a new baby to your codebase. You should give the class a very good name. Although the only limit of your class name is the rules of a legal Python variable (e.g., can’t start with a number), there are preferred ways to give class names.

當您定義自己的類時,您要在代碼庫中添加一個新的嬰兒。 您應該給全班一個很好的名字。 盡管類名的唯一限制是合法的Python變量的規則(例如,不能以數字開頭),但是有一些首選的方法來提供類名。

  • Use nouns that are easy to pronounce. It’s especially important if you work on a team project. During a group presentation, you probably don’t want to be the person to say, “in this case, we create an instance of the Zgnehst class.” In addition, being easy to pronounce also means the name shouldn’t be too long. I can barely think of cases when you need to use more than three words to define a class name. One word is best, two words are good, and three words are the limit.

    使用易于發音的名詞。 如果您在團隊項目中工作,這一點尤其重要。 在小組演講中,您可能不想成為這樣的人:“在這種情況下,我們創建Zgnehst類的實例。” 另外,易于發音也意味著名稱不應太長。 當您需要使用三個以上的單詞來定義類名時,我幾乎無法想到。 一個字是最好的,兩個字是好,三個字是極限。

  • Reflect its stored data and intended functionalities. It’s like in our real life — boys are given boy names. When we see boy names, we expect the kids are boys. It applies to class names too (or any other variables in general). The rule is simple — Don’t surprise people. If you’re dealing with the students’ information, the class should be named Student. KiddosAtCampus isn’t making the most common sense.

    反映其存儲的數據和預期的功能。 就像在我們的現實生活中一樣-男孩被賦予男孩名字。 當我們看到男孩的名字時,我們期望孩子是男孩。 它也適用于類名(或通常的任何其他變量)。 規則很簡單 -不要讓人們感到驚訝。 如果您要處理學生的信息,則該班級應命名為Student。 KiddosAtCampus并不是最常識。

  • Follow naming conventions. We should use upper-case camel style for class names, like GoodName. The following is an incomplete list of unconventional class names: goodName, Good_Name, good_name, and GOodnAme. Following naming conventions is to make your intention clear. When people read your code, they can safely assume that an object with names like GoodName is a class.

    遵循命名約定。 我們應該對類名使用大寫的駝色樣式,例如GoodName。 以下是非常規類名稱的不完整列表:goodName,Good_Name,good_name和GOodnAme。 遵循命名約定是為了使您的意圖明確。 當人們閱讀您的代碼時,他們可以安全地假定名稱如GoodName的對象是一個類。

There are also naming rules and conventions that apply to attributes and functions. In the below sections, I’ll briefly mention them where applicable, but the overall principles are the same. The only rule of thumb is simple: Don’t surprise people.

也有適用于屬性和功能的命名規則和約定。 在以下各節中,我將在適用的地方簡要提及它們,但是總體原理是相同的。 唯一的經驗法則很簡單:不要讓人們感到驚訝。

2.顯式實例屬性 (2. Explicit Instance Attributes)

In most cases, we want to define our own instance initialization method (i.e., __init__). In this method, we set the initial state of our newly created instances of the class. However, Python doesn’t restrict where you can define instance attributes with custom classes. In other words, you can define additional instance attributes in later operations after the instance has been created. The following code shows you a possible scenario.

在大多數情況下,我們想定義自己的實例初始化方法(即__init__ )。 在此方法中,我們設置了新創建的類實例的初始狀態。 但是,Python并沒有限制您可以使用自定義類定義實例屬性的位置。 換句話說,您可以在創建實例之后的后續操作中定義其他實例屬性。 以下代碼顯示了一種可能的情況。

Initialization Method
初始化方法

As shown above, we can create an instance of the Student class by specifying a student’s first and last names. Later, when we call the instance method (i.e., verify_registration_status), the Student instance’s status attribute will be set. However, this isn’t the desired pattern, because if you spread various instance attributes throughout the entire class, you’re not making the class clear what data an instance object holds. Thus, the best practice is to place an instance’s attributes in the __init__ method, such that your code’s reader has a single place to get to know your class’s data structure, as shown below.

如上所示,我們可以通過指定學生的名字和姓氏來創建Student類的實例。 稍后,當我們調用實例方法(即verify_registration_status )時,將設置Student實例的status屬性。 但是,這不是理想的模式,因為如果您在整個類中散布各種實例屬性,則不會使類明確實例對象擁有的數據。 因此,最佳實踐是將實例的屬性放在__init__方法中,這樣您的代碼閱讀器就可以通過一個地方來了解類的數據結構,如下所示。

Better Initialization Method
更好的初始化方法

For those instance attributes that you can’t set initially, you can set them with placeholder values, such as None. Although it’s of less concern, this change also helps prevent the possible error when you forget to call some instance methods to set the applicable instance attributes, causing AttributeError (‘Student’ object has no attribute ‘status_verified’).

對于最初無法設置的那些實例屬性,可以使用占位符值(例如None 。 盡管'Student' object has no attribute 'status_verified'擔心,但是當您忘記調用某些實例方法來設置適用的實例屬性時,此更改還有助于防止可能的錯誤,從而導致AttributeError ( 'Student' object has no attribute 'status_verified' )。

In terms of the naming rules, the attributes should be named using lower cases and follow the snake case style, which means that if you use multiple words, connect them with underscores. Moreover, all the names should have meaningful indication regarding what data it holds (e.g., first_name is better than fn).

就命名規則而言,屬性應使用小寫字母命名,并遵循蛇形字母樣式,這意味著如果您使用多個單詞,請使用下劃線將它們連接起來。 此外,所有名稱都應具有關于所保存數據的有意義的指示(例如, first_namefn更好)。

3.使用屬性-但精簡 (3. Use Properties — But Parsimoniously)

Some people learn Python coding with an existing background of other OOP languages, such as Java, and they’re used to creating getters and setters for attributes of the instances. This pattern can be mimicked with the use of the property decorator in Python. The following code shows you the basic form of using the property decorator to implement getters and setters.

有些人在其他OOP語言(例如Java)的現有背景下學習Python編碼,并且習慣于為實例的屬性創建getter和setter。 可以通過在Python中使用屬性裝飾器來模仿此模式。 以下代碼顯示了使用屬性裝飾器實現getter和setter的基本形式。

Property Decorator
物業裝飾

Once this property is created, we can use it as regular attributes using the dot notation, although it’s implemented using functions under the hood.

創建此屬性后,我們可以使用點符號將其用作常規屬性,盡管它是通過內部函數實現的。

Use Properties
使用屬性

As you may know, the advantages of using property implementations include verification of proper value settings (check a string is used, not an integer) and read-only access (by not implementing the setter method). However, you should use properties parsimoniously. It can be very distracting if your custom class looks like the below — there are too many properties!

如您所知,使用屬性實現的優點包括驗證正確的值設置(檢查是否使用字符串,而不是整數)和只讀訪問權限(通過不實現setter方法)。 但是,您應該同時使用屬性。 如果您的自定義類如下所示,可能會很讓人分心–屬性太多!

Abuse of Properties
濫用財產

In most cases, these properties can be replaced with instance attributes, and thus we can access them and set them directly. Unless you have specific needs for the benefits of using properties as discussed (e.g., value verification), using attributes is preferred over creating properties in Python.

在大多數情況下,這些屬性可以用實例屬性代替,因此我們可以訪問它們并直接設置它們。 除非您對使用屬性(如討論的值)的好處有特定的需求,否則使用屬性優先于在Python中創建屬性。

4.定義有意義的字符串表示 (4. Define Meaningful String Representations)

In Python, functions that have double underscores before and after the name are referred to as special or magic methods, and some people call them dunder methods. They have special usages for basic operations by the interpreter, including the __init__ method that we’ve covered previously. Two special methods, __repr__ and __str__, are essential for creating proper string representations of your custom class, which will give the code readers more intuitive information about your classes.

在Python中,名稱前后帶有雙下劃線的函數稱為特殊方法或魔術方法,有些人將其稱為dunder方法。 它們對解釋器的基本操作有特殊的用法,包括我們先前介紹的__init__方法。 兩種特殊方法__repr____str__對于創建自定義類的正確字符串表示形式至關重要,這將為代碼閱讀器提供有關類的更直觀信息。

Between them, the major difference is that the __repr__ method defines the string, using which you can re-create the object by calling eval(repr(“the repr”)), while the __str__ method defines the string that is more descriptive and allows more customization. In other words, you can think that the string defined in the __repr__ method is to be viewed by developers while that used in the __str__ method is to be viewed by regular users. The following shows you an example.

它們之間的主要區別在于__repr__方法定義了字符串,使用該字符串可以通過調用eval(repr(“the repr”))來重新創建對象,而__str__方法定義的字符串則更具描述性并允許更多定制。 換句話說,您可以認為__repr__方法中定義的字符串將由開發人員查看,而__str__方法中使用的__str__將由常規用戶查看。 下面顯示了一個示例。

Implementation of String Representations
字符串表示的實現

Please note that in the __repr__ method’s implementation (Line 7), the f-string uses !r which will show these strings with quotation marks, because they’re necessary to construct the instance with strings properly formatted. Without the !r formatting, the string will be Student(John, Smith), which isn’t the correct way to construct a Student instance. Let’s see how these implementations show the strings for us. Specifically, the __repr__ method is called when you access the object in the interactive interpreter, while the __str__ method is called by default when you print the object.

請注意,在__repr__方法的實現(第7行)中,f字符串使用!r ,它將用引號顯示這些字符串,因為使用正確格式的字符串構造實例是必需的。 如果沒有!r格式,則字符串將為Student(John, Smith) ,這不是構造Student實例的正確方法。 讓我們看看這些實現如何為我們顯示字符串。 具體來說, __repr__而該方法時,您在交互式解釋器訪問該對象調用, __str__方法默認情況下,當你打印的對象調用。

String Representations
字符串表示

5.實例,類和靜態方法 (5. Instance, Class, and Static Methods)

In a class, we can define three kinds of methods: instance, class, and static methods. You need to consider what methods you should use for the functionalities of concern. Here are some general guidelines.

在一個類中,我們可以定義三種方法:實例,類和靜態方法。 您需要考慮針對所關注的功能應使用哪些方法。 以下是一些一般準則。

If the methods are concerned with individual instance objects, for example, you need to access or update particular attributes of an instance, in which cases, you should use instance methods. These methods have a signature like this: def do_something(self):, in which the self argument refers to the instance object that calls the method. To know more about the self argument, you can refer to my previous article on this topic.

例如,如果方法與單個實例對象有關,則需要訪問或更新實例的特定屬性,在這種情況下,應使用實例方法。 這些方法具有如下簽名: def do_something(self):其中self參數引用調用該方法的實例對象。 要了解有關self參數的更多信息,可以參考我以前關于該主題的文章 。

If the methods are not concerned with individual instance objects, you should consider using class or static methods. Both methods can be easily defined with applicable decorators: classmethod and staticmethod. The difference between these two is that class methods allow you to access or update attributes related to the class, while static methods are independent of any instance or the class itself. A common example of a class method is providing a convenience instantiation method, while a static method can be simply a utility function. The following code shows you some examples.

如果方法與單個實例對象無關,則應考慮使用類或靜態方法。 可以使用適用的修飾符輕松定義這兩種方法: classmethodstaticmethod 。 兩者之間的區別在于,類方法允許您訪問或更新與類相關的屬性,而靜態方法則獨立于任何實例或類本身。 類方法的一個常見示例是提供一種方便的實例化方法,而靜態方法可以只是一個實用函數。 以下代碼為您提供了一些示例。

Different Kinds of Methods
不同種類的方法

In a similar fashion, you can also create class attributes. Unlike instance attributes that we discussed earlier, class attributes are shared by all instance objects, and they should reflect some characteristics independent of individual instance objects.

您也可以類似的方式創建類屬性。 與前面討論的實例屬性不同,類屬性由所有實例對象共享,并且它們應反映一些獨立于各個實例對象的特征。

6.使用私有屬性進行封裝 (6. Encapsulation Using Private Attributes)

When you write custom classes for your project, you need to take into account encapsulation, especially if you’re expecting that others will use your classes too. When the functionalities of the class grow, some functions or attributes are only relevant for data processing within the class. In other words, outside the class, these functions won’t be called and other users of your class won’t even care about the implementation details of these functions. In these scenarios, you should consider encapsulation.

在為項目編寫自定義類時,需要考慮封裝性,尤其是在期望其他人也將使用您的類的情況下。 當類的功能增長時,某些功能或屬性僅與類內的數據處理相關。 換句話說,在類之外,將不會調用這些函數,并且您的類的其他用戶甚至不會關心這些函數的實現細節。 在這些情況下,您應該考慮封裝。

One important way to apply encapsulation is to prefix attributes and functions with an underscore or two underscores, as a convention. The subtle difference is that those with an underscore are considered protected, while those with two underscores are considered private, which involves name-mangling after its creation. Differentiating these two categories is beyond the scope of the present article, and one of my previous articles have covered them.

按照慣例,應用封裝的一種重要方法是為屬性和函數加上下劃線或兩個下劃線。 細微的區別是帶有下劃線的人被認為是受保護的 ,而帶有兩個下劃線的人被認為是private ,這涉及在其創建后進行名稱處理。 區分這兩個類別不在本文的討論范圍之內,而我以前的文章之一已經涵蓋了它們。

In essence, by naming attributes and functions this way, you’re telling the IDEs (i.e., integrated development environment, such as PyCharm) that they’re not going to be accessed outside the class, although true private attributes don’t exist in Python. In other words, they’re still accessible if we choose so.

本質上,通過這樣命名屬性和函數,是在告訴IDE(即集成開發環境,例如PyCharm),盡管在類中不存在真正的私有屬性,但它們不會在類外部訪問。Python。 換句話說,如果我們選擇它們,它們仍然可以訪問。

Encapsulation
封裝形式

The above code shows you a trivial example of encapsulation. For a student, we may be interested in knowing their average GPA, and we can get the point using the get_mean_gpa method. The user doesn’t need to know how the mean GPA is calculated, such that we can make related methods protected by placing an underscore prefixing the function names.

上面的代碼向您展示了一個簡單的封裝示例。 對于一個學生,我們可能會對了解他們的平均GPA感興趣,我們可以使用get_mean_gpa方法獲得get_mean_gpa 。 用戶不需要知道平均GPA的計算方式,因此我們可以通過在函數名稱前添加下劃線來保護相關方法。

The key takeaway for this best practice is that you expose only the minimal number of public APIs that are relevant for the users to use your code. For those that are used only internally, make them protected or private methods.

此最佳實踐的主要收獲是,您僅公開與用戶使用您的代碼相關的最少數量的公共API。 對于僅在內部使用的那些,請將其設置為受保護的方法或私有方法。

7.單獨的關注點和解耦 (7. Separate Concerns and Decoupling)

With the development of your project, you find out that you’re dealing with more data, your class can become cumbersome if you’re sticking to one single class. Let’s continue with the example of the Student class. Suppose that students have lunch at school, and each of them has a dining account that they can use to pay for meals. Theoretically, we can deal with account-related data and functionalities within the Student class, as shown below.

隨著項目的發展,您發現自己正在處理更多的數據,如果您堅持一個單一的班級,那么您的班級可能會變得很麻煩。 讓我們繼續學生類的示例。 假設學生在學校吃午餐,并且每個人都有一個餐飲帳戶,可以用來支付餐費。 從理論上講,我們可以處理Student類中與帳戶相關的數據和功能,如下所示。

Mixed Functionalities
混合功能

The above code shows you some pseudocode on checking account balance and loading money to the account, both of which are implemented in the Student class. Imagine that there are more operations that can be related to the account, such as suspending a lost card, consolidating accounts — to implement all of them will make the Student class larger and larger, which make it gradually more difficult to maintain. Instead, you should isolate these responsibilities and make your Student class irresponsible for these account-related functionalities — a design pattern termed as decoupling.

上面的代碼為您提供了一些有關檢查帳戶余額和向帳戶充值的偽代碼,這兩種代碼均在Student類中實現。 想象一下,還有更多與該帳戶相關的操作,例如暫停丟失的卡,合并帳戶-實施所有這些操作將使Student類越來越大,從而使維護學生的難度逐漸增加。 相反,您應該隔離這些責任,并使您的學生班級對這些與帳戶相關的功能不負責任-一種稱為脫鉤的設計模式。

Separated Concerns
分離的問題

The above code shows you how we can design the data structures with an additional Account class. As you can see, we move all account-related operations into the Account class. To retrieve the account information for the student, the Student class will handle the functionality by retrieving information from the Account class. If we want to implement more functions related to the class, we can simply update the Account class only.

上面的代碼向您展示了如何使用附加的Account類設計數據結構。 如您所見,我們將所有與帳戶相關的操作移至Account類。 要檢索學生的帳戶信息, Student類將通過從Account類中檢索信息來處理該功能。 如果我們想實現更多與該類相關的功能,我們只需簡單地更新Account類即可。

The main takeaway for the design pattern is that you want your individual classes to have separate concerns. By having these responsibilities separated, your classes become smaller, which makes future changes easier, because you’ll be dealing with smaller code components.

設計模式的主要要點是,您希望各個類具有單獨的關注點。 通過將這些職責分開,您的類將變小,這將使將來的更改變得更容易,因為您將處理較小的代碼組件。

8.考慮__slots__進行優化 (8. Consider __slots__ For Optimization)

If your class is used mostly as data containers for storing data only, you can consider using __slots__ to optimize the performance of your class. It doesn’t only increase the speed of attribute accessing but also saves memory, which can be a big benefit if you need to create thousands or many more instance objects. The reason is that for a regular class, instance attributes are stored through an internally managed dictionary. By contrast, with the use of the __slots__, instance attributes will be stored using array-related data structures implemented using C under the hood, and their performance is optimized with much higher efficiency.

如果您的類主要用作僅用于存儲數據的數據容器,則可以考慮使用 __slots__ 以優化您的班級表現。 它不僅可以提高屬性訪問的速度,而且可以節省內存,如果您需要創建數千個或更多實例對象,這將是一個很大的好處。 原因是對于常規類,實例屬性是通過內部托管的字典存儲的。 相比之下,通過使用__slots__ ,實例屬性將使用在__slots__使用C實現的與數組相關的數據結構存儲,并且以更高的效率優化了它們的性能。

Use of __slots__ in Class Definition
在類定義中使用__slots__

The above code shows you a trivial example of how we implement the __slots__ in a class. Specifically, you list all the attributes as a sequence, which will create a one-to-one match in data storage for faster access and less memory consumption. As just mentioned, regular classes use a dictionary for attribute accessing but not for those with __slots__ implemented. The following code shows you such a fact.

上面的代碼顯示了一個簡單的示例,說明了我們如何在類中實現__slots__ 。 具體來說,您將所有屬性列為一個序列,這將在數據存儲中創建一對一匹配,以加快訪問速度并減少內存消耗。 如前所述,常規類使用字典進行屬性訪問,但不使用實現__slots__的字典。 以下代碼向您展示了這樣一個事實。

No __dict__ in Classes With __slots__
具有__插槽__的類中沒有__dict__

A detailed discussion of using __slots__ can be found in a nice answer on Stack Overflow, and you can find more information from the official documentation. Regarding the gained benefits of faster access and saved memory, a recent Medium article has a very good demonstration, and I’m not going to expand on this. However, one thing to note is that using __slots__ will have a side effect — it prevents you from dynamically creating additional attributes. Some people propose it as a mechanism for controlling what attributes your class has, but it’s not how it was designed.

有關使用__slots__詳細討論,可以在Stack Overflow上找到一個不錯的答案,您可以從官方文檔中找到更多信息。 關于更快訪問和節省內存所獲得的好處, 最近的《中型》文章很好地演示了這一點,我將不對此進行擴展。 但是,需要注意的一件事是,使用__slots__會產生副作用-它會阻止您動態創建其他屬性。 有人提出將其作為一種控制類具有的屬性的機制,但這并不是它的設計方式。

9.文件 (9. Documentation)

Last, but not least, we have to talk about documentation of your class. Most importantly, we need to understand that writing documents isn’t replacing any code. Writing tons of documents doesn’t improve your code’s performance, and it doesn’t necessarily make your code more readable. If you have to rely on docstrings to clarify your code, it’s very likely that your code has problems. I truly believe that your code should speak all by itself. The following code just shows you a mistake that some programmers can make — using unnecessary comments to compensate for bad code (i.e., meaningless variable names in this case). By contrast, some good code with good names doesn’t even need comments.

最后但并非最不重要的一點,我們必須談論您的課程的文檔。 最重要的是,我們需要了解編寫文檔并不能替代任何代碼。 編寫大量文檔并不能提高代碼的性能,也不一定會使代碼更具可讀性。 如果您必須依靠文檔字符串來澄清代碼,則很可能您的代碼有問題。 我真的相信您的代碼應該自己講。 以下代碼僅向您顯示一些程序員可能犯的一個錯誤-使用不必要的注釋來補償錯誤的代碼(即,在這種情況下,無意義的變量名)。 相比之下,一些帶有好名字的好代碼甚至不需要注釋。

Bad Comment Examples
不良評論示例

I’m not saying that I’m against writing comments and docstrings, but it really depends on your use cases. If your code is used by more than one person or more than one occasion (e.g., you’re the only one accessing the code but for multiple times), you should consider writing some good comments. They can help yourself or your teammates read your code, but no one should assume that your code does exactly what’s said in the comments. In other words, writing good code is always the top priority that you need to keep in mind.

我并不是說我反對寫注釋和文檔字符串,但這實際上取決于您的用例。 如果您的代碼被不止一個人使用或多次使用(例如,您是唯一一次訪問代碼但多次訪問的代碼),則應考慮編寫一些好的注釋。 他們可以幫助您自己或您的隊友閱讀您的代碼,但是沒有人可以假設您的代碼完全符合注釋中的要求。 換句話說,編寫好的代碼始終是您需要牢記的頭等大事。

If particular portions of your code are to be used by end users, you want to write docstrings, because those people aren’t familiar with the relevant codebase. All they want to know is how to use the pertinent APIs, and the docstrings will form the basis for the help menu. Thus, it’s your responsibility as the programmer to make sure that you provide clear instructions on how to use your programs.

如果最終用戶要使用代碼的特定部分,則需要編寫文檔字符串,因為這些人對相關的代碼庫并不熟悉。 他們只想知道如何使用相關的API,而文檔字符串將構成幫助菜單的基礎。 因此,作為程序員,您有責任確保提供有關如何使用程序的明確說明。

結論 (Conclusions)

In this article, we reviewed important factors that you need to consider when you define your own classes. If you’re new to Python or programming in general, you may not fully understand every aspect that we’ve discussed, which is OK. The more you code, the more you’ll find the importance of having these principles in mind before you define your classes. Practice these guidelines continuously when you work with classes because a good design will save much of your development time later.

在本文中,我們回顧了定義自己的類時需要考慮的重要因素。 如果您不熟悉Python或一般編程,那么您可能不會完全了解我們所討論的各個方面,這沒關系。 您編寫的代碼越多,您就越會發現在定義類之前牢記這些原則的重要性。 在上課時,請不斷練習這些準則,因為好的設計會在以后節省很多開發時間。

翻譯自: https://medium.com/better-programming/advanced-python-9-best-practices-to-apply-when-you-define-classes-871a27af658b

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/388022.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/388022.shtml
英文地址,請注明出處:http://en.pswp.cn/news/388022.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Java 注解 攔截器

場景描述:現在需要對部分Controller或者Controller里面的服務方法進行權限攔截。如果存在我們自定義的注解,通過自定義注解提取所需的權限值,然后對比session中的權限判斷當前用戶是否具有對該控制器或控制器方法的訪問權限。如果沒有相關權限…

醫療大數據處理流程_我們需要數據來大規模改善醫療流程

醫療大數據處理流程Note: the fictitious examples and diagrams are for illustrative purposes ONLY. They are mainly simplifications of real phenomena. Please consult with your physician if you have any questions.注意:虛擬示例和圖表僅用于說明目的。 …

What's the difference between markForCheck() and detectChanges()

https://stackoverflow.com/questions/41364386/whats-the-difference-between-markforcheck-and-detectchanges轉載于:https://www.cnblogs.com/chen8840/p/10573295.html

ASP.NET Core中使用GraphQL - 第七章 Mutation

ASP.NET Core中使用GraphQL - 目錄 ASP.NET Core中使用GraphQL - 第一章 Hello WorldASP.NET Core中使用GraphQL - 第二章 中間件ASP.NET Core中使用GraphQL - 第三章 依賴注入ASP.NET Core中使用GraphQL - 第四章 GrahpiQLASP.NET Core中使用GraphQL - 第五章 字段, 參數, 變量…

POM.xml紅叉解決方法

方法/步驟 1用Eclipse創建一個maven工程,網上有很多資料,這里不再啰嗦。 2右鍵maven工程,進行更新 3在彈出的對話框中勾選強制更新,如圖所示 4稍等片刻,pom.xml的紅叉消失了。。。

JS前臺頁面驗證文本框非空

效果圖&#xff1a; 代碼&#xff1a; 源代碼&#xff1a; <script type"text/javascript"> function check(){ var xm document.getElementById("xm").value; if(xm null || xm ){ alert("用戶名不能為空"); return false; } return …

python對象引用計數器_在Python中借助計數器對象對項目進行計數

python對象引用計數器前提 (The Premise) When we deal with data containers, such as tuples and lists, in Python we often need to count particular elements. One common way to do this is to use the count() function — you specify the element you want to count …

套接字設置為(非)阻塞模式

當socket 進行TCP 連接的時候&#xff08;也就是調用connect 時&#xff09;&#xff0c;一旦網絡不通&#xff0c;或者是ip 地址無效&#xff0c;就可能使整個線程阻塞。一般為30 秒&#xff08;我測的是20 秒&#xff09;。如果設置為非阻塞模式&#xff0c;能很好的解決這個…

經典問題之「分支預測」

問題 來源 &#xff1a;stackoverflow 為什么下面代碼排序后累加比不排序快&#xff1f; public static void main(String[] args) {// Generate dataint arraySize 32768;int data[] new int[arraySize];Random rnd new Random(0);for (int c 0; c < arraySize; c)data…

vi

vi filename :打開或新建文件&#xff0c;并將光標置于第一行首 vi n filename &#xff1a;打開文件&#xff0c;并將光標置于第n行首 vi filename &#xff1a;打開文件&#xff0c;并將光標置于最后一行首 vi /pattern filename&#xff1a;打開文件&#xff0c;并將光標置…

數字圖像處理 python_5使用Python處理數字的高級操作

數字圖像處理 pythonNumbers are everywhere in our daily life — there are phone numbers, dates of birth, ages, and other various identifiers (driver’s license and social security numbers, for example).電話號碼在我們的日常生活中無處不在-電話號碼&#xff0c;…

05精益敏捷項目管理——超越Scrum

00.我們不是不知道它會給我們帶來麻煩&#xff0c;只是沒想到麻煩會有這么多。——威爾.羅杰斯 01.知識點&#xff1a; a.Scrum是一個強大、特意設計的輕量級框架&#xff0c;器特性就是將軟件開發中在制品的數量限制在團隊層級&#xff0c;使團隊有能力與業務落班一起有效地開…

帶標題的圖片輪詢展示

為什么80%的碼農都做不了架構師&#xff1f;>>> <div> <table width"671" cellpadding"0" cellspacing"0"> <tr height"5"> <td style"back…

linux java 查找進程中的線程

這里對linux下、sun(oracle) JDK的線程資源占用問題的查找步驟做一個小結&#xff1b;linux環境下&#xff0c;當發現java進程占用CPU資源很高&#xff0c;且又要想更進一步查出哪一個java線程占用了CPU資源時&#xff0c;按照以下步驟進行查找&#xff1a;(一)&#xff1a;通過…

定位匹配 模板匹配 地圖_什么是地圖匹配?

定位匹配 模板匹配 地圖By Marie Douriez, James Murphy, Kerrick Staley瑪麗杜里茲(Marie Douriez)&#xff0c;詹姆斯墨菲(James Murphy)&#xff0c;凱里克史塔利(Kerrick Staley) When you request a ride, Lyft tries to match you with the driver most suited for your…

Sprint計劃列表

轉載于:https://www.cnblogs.com/zhs20160715/p/9953586.html

MySQL學習【第十二篇事務中的鎖與隔離級別】

一.事務中的鎖 1.啥是鎖&#xff1f; 顧名思義&#xff0c;鎖就是鎖定的意思 2.鎖的作用是什么&#xff1f; 在事務ACID的過程中&#xff0c;‘鎖’和‘隔離級別’一起來實現‘I’隔離性的作用 3.鎖的種類 共享鎖&#xff1a;保證在多事務工作期間&#xff0c;數據查詢不會被阻…

Android WebKit

這段時間基于項目需要 在開發中與WebView的接觸比較多&#xff0c;前段時間關于HTML5規范塵埃落定的消息出現在各大IT社區頭版上&#xff0c;更有人說&#xff1a;HTML5將顛覆原生App開發 雖然我不太認同這一點 但是關于HTML5JSCSSNative的跨平臺開發模式還是為很多企業節省了開…

jQuery的事件綁定和解綁

1、綁定事件 語法&#xff1a; bind(type,data,fn) 描述&#xff1a;為每一個匹配元素的特定事件&#xff08;像click&#xff09;綁定一個事件處理器函數。 參數解釋&#xff1a; type (String) : 事件類型 data (Object) : (可選) 作為event.data屬性值傳遞給事件對象的額外數…

軟件測試框架課程考試_那考試準備課程值得嗎?

軟件測試框架課程考試By Levi Petty李維佩蒂(Levi Petty) This project uses a public, synthesized exam scores dataset from Kaggle to analyze average scores in Math, Reading, and Writing subject areas, relative to the student’s parents’ level of education an…