日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python oop编程_Python 3中的面向对象编程(OOP)

發布時間:2024/1/1 python 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python oop编程_Python 3中的面向对象编程(OOP) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

python oop編程

In this article you’ll pick up the following basic concepts of OOP in Python:

在本文中,您將了解Python中OOP的以下基本概念:

  • Python Classes
  • Object Instances
  • Defining and Working with Methods
  • OOP Inheritance
  • Python類
  • 對象實例
  • 定義和使用方法
  • OOP繼承

Free Bonus: Click here to get access to a free Python OOP Cheat Sheet that points you to the best tutorials, videos, and books to learn more about Object-Oriented Programming with Python.

免費獎金: 單擊此處可獲取免費的Python OOP作弊表 ,該指南將為您提供最佳的教程,視頻和書籍,以了解有關使用Python進行面向對象編程的更多信息。

什么是面向對象編程(OOP)? (What Is Object-Oriented Programming (OOP)?)

Object-oriented Programming, or OOP for short, is a programming paradigm which provides a means of structuring programs so that properties and behaviors are bundled into individual objects.

面向對象編程(簡稱OOP)是一種編程范例 ,它提供了一種結構化程序的方法,以便將屬性和行為捆綁到單個對象中。

For instance, an object could represent a person with a name property, age, address, etc., with behaviors like walking, talking, breathing, and running. Or an email with properties like recipient list, subject, body, etc., and behaviors like adding attachments and sending.

例如,一個對象可以代表一個具有名稱屬性,年齡,住所等的人,并具有走路,說話,呼吸和奔跑等行為。 或具有諸如收件人列表,主題,正文等屬性以及添加附件和發送等行為的電子郵件。

Put another way, object-oriented programming is an approach for modeling concrete, real-world things like cars as well as relations between things like companies and employees, students and teachers, etc. OOP models real-world entities as software objects, which have some data associated with them and can perform certain functions.

換句話說,面向對象的編程是一種對汽車等具體的現實世界事物以及公司與員工,學生和教師等事物之間的關系進行建模的方法。OOP將現實世界的實體建模為軟件對象,與它們相關聯的一些數據,并可以執行某些功能。

Another common programming paradigm is procedural programming which structures a program like a recipe in that it provides a set of steps, in the form of functions and code blocks, which flow sequentially in order to complete a task.

另一個常見的編程范例是過程編程,該過程以配方的形式構造程序,因為它以功能和代碼塊的形式提供了一組步驟,這些步驟順序地流動以完成任務。

The key takeaway is that objects are at the center of the object-oriented programming paradigm, not only representing the data, as in procedural programming, but in the overall structure of the program as well.

關鍵要點在于,對象是面向對象編程范式的中心,不僅像過程編程中那樣代表數據,而且在程序的整體結構中也是如此。

NOTE: Since Python is a multi-paradigm programming language, you can choose the paradigm that best suits the problem at hand, mix different paradigms in one program, and/or switch from one paradigm to another as your program evolves.

注意 :由于Python是一種多范例編程語言,因此您可以選擇最適合當前問題的范例,在一個程序中混合使用不同的范例,和/或隨著程序的發展從一個范例切換到另一個范例。

Python中的類 (Classes in Python)

Focusing first on the data, each thing or object is an instance of some class.

首先關注數據,每個事物或對象都是某個類的實例。

The primitive data structures available in Python, like numbers, strings, and lists are designed to represent simple things like the cost of something, the name of a poem, and your favorite colors, respectively.

Python中可用的原始數據結構,例如數字,字符串和列表,旨在分別表示簡單的事物,例如某物的成本,一首詩的名字和您喜歡的顏色。

What if you wanted to represent something much more complicated?

如果您想代表更復雜的事情怎么辦?

For example, let’s say you wanted to track a number of different animals. If you used a list, the first element could be the animal’s name while the second element could represent its age.

例如,假設您要跟蹤許多不同的動物。 如果使用列表,則第一個元素可以是動物的名字,而第二個元素可以代表動物的年齡。

How would you know which element is supposed to be which? What if you had 100 different animals? Are you certain each animal has both a name and an age, and so forth? What if you wanted to add other properties to these animals? This lacks organization, and it’s the exact need for classes.

您怎么知道哪個元素應該是哪個? 如果您有100種不同的動物怎么辦? 您確定每個動物都有名字和年齡,等等嗎? 如果您想為這些動物添加其他屬性怎么辦? 這缺乏組織性,而這正是上課的真正需要。

Classes are used to create new user-defined data structures that contain arbitrary information about something. In the case of an animal, we could create an Animal() class to track properties about the Animal like the name and age.

類用于創建新的用戶定義的數據結構,其中包含有關某事的任意信息。 對于動物,我們可以創建Animal()類來跟蹤有關Animal的屬性,例如名稱和年齡。

It’s important to note that a class just provides structure—it’s a blueprint for how something should be defined, but it doesn’t actually provide any real content itself. The Animal() class may specify that the name and age are necessary for defining an animal, but it will not actually state what a specific animal’s name or age is.

重要的是要注意,一個類僅提供結構-它是應該如何定義內容的藍圖,但實際上它本身并不提供任何實際內容。 Animal()類可能會指定名稱和年齡對于定義動物是必需的,但實際上并不會說明特定動物的名稱或年齡。

It may help to think of a class as an idea for how something should be defined.

將類視為如何定義某些內容的想法可能會有所幫助。

Python對象(實例) (Python Objects (Instances))

While the class is the blueprint, an instance is a copy of the class with actual values, literally an object belonging to a specific class. It’s not an idea anymore; it’s an actual animal, like a dog named Roger who’s eight years old.

雖然類是藍圖,但實例是具有實際值的類的副本,實際上是屬于特定類的對象。 這已經不是一個主意了。 它是一種真實的動物,就像八歲的名叫羅杰的狗一樣。

Put another way, a class is like a form or questionnaire. It defines the needed information. After you fill out the form, your specific copy is an instance of the class; it contains actual information relevant to you.

換句話說,課程就像表格或問卷。 它定義了所需的信息。 填寫表格后,您的特定副本是該類的實例; 它包含與您有關的實際信息。

You can fill out multiple copies to create many different instances, but without the form as a guide, you would be lost, not knowing what information is required. Thus, before you can create individual instances of an object, we must first specify what is needed by defining a class.

您可以填寫多個副本來創建許多不同的實例,但是如果沒有該表格的指導,您將會迷失方向,不知道需要什么信息。 因此,在創建對象的單個實例之前,我們必須首先通過定義類來指定所需的對象。

如何在Python中定義類 (How To Define a Class in Python)

Defining a class is simple in Python:

在Python中定義類很簡單:

class class DogDog (( objectobject ):):pass pass

You start with the class keyword to indicate that you are creating a class, then you add the name of the class (using CamelCase notation, starting with a capital letter), and finally add the class that you are inheriting from in parentheses (more on this below).

您從class關鍵字開始以指示您正在創建一個類,然后添加該類的名稱(使用CamelCase表示法 ,以大寫字母開頭),最后在括號中添加您要從其繼承的類(更多信息下面)。

Also, we used the Python keyword pass here. This is very often used as a place holder where code will eventually go. It allows us to run this code without throwing an error.

另外,我們在這里使用了Python關鍵字pass 。 這通常被用作占位符,代碼將最終進入該占位符。 它使我們能夠運行此代碼而不會引發錯誤。

實例屬性 (Instance Attributes)

All classes create objects, and all objects contain characteristics called attributes (referred to as properties in the opening paragraph). Use the __init__() method to initialize (e.g., specify) an object’s initial attributes by giving them their default value (or state). This method must have at least one argument as well as the self variable, which refers to the object itself (e.g., Dog).

所有類都創建對象,并且所有對象都包含稱為屬性的特征(在開始的段落中稱為屬性)。 使用__init__()方法通過為其提供默認值(或狀態)來初始化(例如,指定)對象的初始屬性。 此方法必須至少具有一個參數以及self變量,該self變量引用對象本身(例如Dog)。

In the case of our Dog() class, each dog has a specific name and age, which is obviously important to know for when you start actually creating different dogs. Remember: the class is just for defining the Dog, not actually creating instances of individual dogs with specific names and ages; we’ll get to that shortly.

就我們的Dog()類而言,每只狗都有一個特定的名稱和年齡,當您開始實際創建其他狗時,要知道這一點很重要。 請記住:該類僅用于定義Dog,而不是實際創建具有特定名稱和年齡的單個狗的實例; 我們將盡快解決。

Similarly, the self variable is also an instance of the class. Since instances of a class have varying values we could state Dog.name = name rather than self.name = name. But since not all dogs share the same name, we need to be able to assign different values to different instances. Hence the need for the special self variable, which will help to keep track of individual instances of each class.

同樣, self變量也是該類的實例。 由于類的實例具有不同的值,因此我們可以聲明Dog.name = name而不是self.name = name 。 但是由于并非所有的狗都有相同的名字,因此我們需要能夠為不同的實例分配不同的值。 因此,需要特殊的self變量,這將有助于跟蹤每個類的各個實例。

NOTE: You will never have to call the __init__() method; it gets called automatically when you create a new ‘Dog’ instance.

注意 :您將永遠不必調用__init__()方法。 創建新的“狗”實例時會自動調用它。

類屬性 (Class Attributes)

While instance attributes are specific to each object, class attributes are the same for all instances—which in this case is all dogs.

盡管實例屬性是每個對象專用的,但類屬性對于所有實例都是相同的,在這種情況下,它是所有狗。

class class DogDog (( objectobject ):):# Class Attribute# Class Attributespecies species = = 'mammal''mammal'# Initializer / Instance Attributes# Initializer / Instance Attributesdef def __init____init__ (( selfself , , namename , , ageage ):):selfself .. name name = = namenameselfself .. age age = = age age

So while each dog has a unique name and age, every dog will be a mammal.

因此,盡管每只狗都有自己獨特的名字和年齡,但每只狗都是哺乳動物。

Let’s create some dogs…

讓我們來創造一些狗...

實例化對象 (Instantiating Objects)

Instantiating is a fancy term for creating a new, unique instance of a class.

實例化是一個奇特的術語,用于創建類的新的唯一實例。

For example:

例如:

We started by defining a new Dog() class, then created two new dogs, each assigned to different objects. So, to create an instance of a class, you use the the class name, followed by parentheses. Then to demonstrate that each instance is actually different, we instantiated two more dogs, assigning each to a variable, then tested if those variables are equal.

我們首先定義一個新的Dog()類,然后創建兩個新的狗,每個狗分配給不同的對象。 因此,要創建類的實例,請使用類名稱,后跟括號。 然后,為了證明每個實例實際上是不同的,我們實例化了另外兩個狗,將每個狗分配給一個變量,然后測試這些變量是否相等。

What do you think the type of a class instance is?

您認為類實例的類型是什么?

>>> >>> class class DogDog (( objectobject ): ): ... ... pass pass ... ... >>> >>> a a = = DogDog () () >>> >>> typetype (( aa ) ) <type 'instance'> <type 'instance'>

Let’s look at a slightly more complex example…

讓我們看一個更復雜的例子……

NOTE: Notice how we use dot notation to access attributes from each object.

注意 :請注意我們如何使用點符號來訪問每個對象的屬性。

Save this as dog_class.py, then run the program. You should see:

將其另存為dog_class.py,然后運行程序。 您應該看到:

Philo is 5 and Mikey is 6. Philo is a mammal! Philo is 5 and Mikey is 6. Philo is a mammal!

這是怎么回事? (What’s Going On?)

We created a new instance of the Dog() class and assigned it to the variable philo. We then passed it two arguments, "Philo" and 5, which represent that dog’s name and age, respectively.

我們創建了Dog()類的新實例,并將其分配給變量philo 。 然后,我們將兩個參數"Philo"和5傳遞給它,分別代表那只狗的名字和年齡。

These attributes are passed to the __init__ method, which gets called any time you create a new instance, attaching the name and age to the object. You might be wondering why we didn’t have to pass in the self argument.

這些屬性將傳遞給__init__方法,該方法在您創建新實例時會被調用,并將名稱和年齡附加到對象上。 您可能想知道為什么我們不必傳遞self論證。

This is Python magic; when you create a new instance of the class, Python automatically determines what self is (a Dog in this case) and passes it to the __init__ method.

這是Python的魔力; 當您創建該類的新實例時,Python會自動確定什么是self (在本例中為Dog)并將其傳遞給__init__方法。

復習練習(#1) (Review Exercises (#1))

“The Oldest Dog” Show/Hide

“最老的狗” 節目/隱藏

Using the same Dog() class, instantiate three new dogs, each with a different age. Then write a function called, get_biggest_number(), that takes any number of ages (*args) and returns the oldest one. Then output the age of the oldest dog like so:

使用相同的Dog()類,實例化三只新狗,每只狗的年齡不同。 然后編寫一個名為get_biggest_number()的函數,該函數可以使用任意多個年齡( *args ),并返回最舊的年齡。 然后像這樣輸出最老的狗的年齡:

實例方法 (Instance Methods)

Instance methods are defined inside a class and are used to get the contents of an instance. They can also be used to perform operations with the attributes of our objects. Like the __init__ method, the first argument is always self:

實例方法是在類內部定義的,用于獲取實例的內容。 它們還可以用于執行具有我們對象屬性的操作。 像__init__方法一樣,第一個參數始終是self :

class class DogDog (( objectobject ):):# Class Attribute# Class Attributespecies species = = 'mammal''mammal'# Initializer / Instance Attributes# Initializer / Instance Attributesdef def __init____init__ (( selfself , , namename , , ageage ):):selfself .. name name = = namenameselfself .. age age = = ageage# instance method# instance methoddef def descriptiondescription (( selfself ):):return return "{} is {} years old""{} is {} years old" .. formatformat (( selfself .. namename , , selfself .. ageage ))# instance method# instance methoddef def speakspeak (( selfself , , soundsound ):):return return "{} says {}""{} says {}" .. formatformat (( selfself .. namename , , soundsound ))# Instantiate the Dog object # Instantiate the Dog object mikey mikey = = DogDog (( "Mikey""Mikey" , , 66 ))# call our instance methods # call our instance methods printprint (( mikeymikey .. descriptiondescription ()) ()) printprint (( mikeymikey .. speakspeak (( "Gruff Gruff""Gruff Gruff" )) ))

Save this as dog_instance_methods.py, then run it:

將其另存為dog_instance_methods.py,然后運行:

In the latter method, speak(), we are defining behavior. What other behaviors could you assign to a dog? Look back to the beginning paragraph to see some example behaviors for other objects.

在后一種方法中, speak()定義了行為。 您還能賦予狗其他哪些行為? 回到開始的段落,以查看其他對象的一些示例行為。

修改屬性 (Modifying Attributes)

You can change the value of attributes based on some behavior:

您可以根據某些行為來更改屬性的值:

>>> >>> class class EmailEmail (( objectobject ): ): ... ... is_sent is_sent = = False False ... ... def def send_emailsend_email (( selfself ): ): ... ... selfself .. is_sent is_sent = = True True ... ... >>> >>> my_email my_email = = EmailEmail () () >>> >>> my_emailmy_email .. is_sent is_sent False False >>> >>> my_emailmy_email .. send_emailsend_email () () >>> >>> my_emailmy_email .. is_sent is_sent True True

Here, we added a method to send an email, which updates the is_sent variable to True.

在這里,我們添加了一種發送電子郵件的方法,該方法將is_sent變量更新為True 。

Python對象繼承 (Python Object Inheritance)

Inheritance is the process by which one class takes on the attributes and methods of another. Newly formed classes are called child classes, and the classes that child classes are derived from are called parent classes.

繼承是一個類繼承另一個類的屬性和方法的過程。 新形成的類稱為子類,子類派生自的類稱為父類。

It’s important to note that child classes override or extend the functionality (e.g., attributes and behaviors) of parent classes. In other words, child classes inherit all of the parent’s attributes and behaviors but can also specify different behavior to follow. The most basic type of class is an object, which generally all other classes inherit as their parent.

重要的是要注意,子類會覆蓋或擴展父類的功能(例如,屬性和行為)。 換句話說,子類繼承了父級的所有屬性和行為,但也可以指定要遵循的不同行為。 類的最基本類型是object ,通常所有其他類都作為其父類繼承。

狗公園的例子 (Dog Park Example)

Let’s pretend that we’re at a dog park. There are multiple Dog objects engaging in Dog behaviors, each with different attributes. In regular-speak that means some dogs are running, while some are stretching and some are just watching other dogs. Furthermore, each dog has been named by its owner and, since each dog is living and breathing, each ages.

假裝我們在狗公園里。 有多個Dog對象參與Dog行為,每個對象具有不同的屬性。 通常來說,這意味著有些狗在奔跑,有些在伸展,有些在看著其他狗。 此外,每只狗都由其主人命名,并且由于每只狗都在生活和呼吸,因此每個年齡段都有。

What’s another way to differentiate one dog from another? How about the dog’s breed:

區分一只狗和另一只狗的另一種方法是什么? 那只狗的品種怎么樣:

Each breed of dog has slightly different behaviors. To take these into account, let’s create separate classes for each breed. These are child classes of the parent Dog class.

每個品種的狗都有略有不同的行為。 為了考慮這些因素,讓我們為每個品種創建單獨的類。 這些是父級Dog類的子類。

擴展父類的功能 (Extending the Functionality of a Parent Class)

Create a new file called dog_inheritance.py:

創建一個名為dog_inheritance.py的新文件:

# Parent class # Parent class class class DogDog (( objectobject ):):# Class attribute# Class attributespecies species = = 'mammal''mammal'# Initializer / Instance attributes# Initializer / Instance attributesdef def __init____init__ (( selfself , , namename , , ageage ):):selfself .. name name = = namenameselfself .. age age = = ageage# instance method# instance methoddef def descriptiondescription (( selfself ):):return return "{} is {} years old""{} is {} years old" .. formatformat (( selfself .. namename , , selfself .. ageage ))# instance method# instance methoddef def speakspeak (( selfself , , soundsound ):):return return "{} says {}""{} says {}" .. formatformat (( selfself .. namename , , soundsound ))# child class (inherits from Dog class) # child class (inherits from Dog class) class class RussellTerrierRussellTerrier (( DogDog ):):def def runrun (( selfself , , speedspeed ):):return return "{} runs {}""{} runs {}" .. formatformat (( selfself .. namename , , speedspeed ))# child class (inherits from Dog class) # child class (inherits from Dog class) class class BulldogBulldog (( DogDog ):):def def runrun (( selfself , , speedspeed ):):return return "{} runs {}""{} runs {}" .. formatformat (( selfself .. namename , , speedspeed ))# child classes inherit attributes and # child classes inherit attributes and # behaviors from the parent class # behaviors from the parent class jim jim = = BulldogBulldog (( "Jim""Jim" , , 1212 ) ) print print jimjim .. descriptiondescription ()()# child classes have specific attributes # child classes have specific attributes # and behaviors as well # and behaviors as well print print jimjim .. runrun (( "slowly""slowly" ) )

Read the comments aloud as you work through this program to help you understand what’s happening, then before you run the program, see if you can predict the expected output.

在閱讀本程序的過程中,請大聲閱讀注釋,以幫助您了解發生了什么,然后在運行該程序之前,查看是否可以預測預期的輸出。

You should see:

您應該看到:

We haven’t added any special attributes or methods to differentiate a RussellTerrier from a Bulldog, but since they’re now two different classes, we could for instance give them different class attributes defining their respective speeds.

我們沒有添加任何特殊的屬性或方法來區分RussellTerrier和Bulldog ,但是由于它們現在是兩個不同的類,因此我們可以為它們提供不同的類屬性,以定義各自的速度。

家長與孩子班 (Parent vs. Child Classes)

The isinstance() function is used to determine if an instance is also an instance of a certain parent class.

isinstance()函數用于確定實例是否也是某個父類的實例。

Save this as dog_isinstance.py:

將此另存為dog_isinstancetance.py:

# Parent class # Parent class class class DogDog (( objectobject ):):# Class attribute# Class attributespecies species = = 'mammal''mammal'# Initializer / Instance attributes# Initializer / Instance attributesdef def __init____init__ (( selfself , , namename , , ageage ):):selfself .. name name = = namenameselfself .. age age = = ageage# instance method# instance methoddef def descriptiondescription (( selfself ):):return return "{} is {} years old""{} is {} years old" .. formatformat (( selfself .. namename , , selfself .. ageage ))# instance method# instance methoddef def speakspeak (( selfself , , soundsound ):):return return "{} says {}""{} says {}" .. formatformat (( selfself .. namename , , soundsound ))# child class (inherits from Dog() class) # child class (inherits from Dog() class) class class RussellTerrierRussellTerrier (( DogDog ):):def def runrun (( selfself , , speedspeed ):):return return "{} runs {}""{} runs {}" .. formatformat (( selfself .. namename , , speedspeed ))# child class (inherits from Dog() class) # child class (inherits from Dog() class) class class BulldogBulldog (( DogDog ):):def def runrun (( selfself , , speedspeed ):):return return "{} runs {}""{} runs {}" .. formatformat (( selfself .. namename , , speedspeed ))# child classes inherit attributes and # child classes inherit attributes and # behaviors from the parent class # behaviors from the parent class jim jim = = BulldogBulldog (( "Jim""Jim" , , 1212 ) ) printprint (( jimjim .. descriptiondescription ())())# child classes have specific attributes # child classes have specific attributes # and behaviors as well # and behaviors as well printprint (( jimjim .. runrun (( "slowly""slowly" ))))# is jim an instance of Dog()? # is jim an instance of Dog()? printprint (( isinstanceisinstance (( jimjim , , DogDog ))))# is julie an instance of Dog()? # is julie an instance of Dog()? julie julie = = DogDog (( "Julie""Julie" , , 100100 ) ) printprint (( isinstanceisinstance (( juliejulie , , DogDog ))))# is johnny walker an instance of Bulldog() # is johnny walker an instance of Bulldog() johnnywalker johnnywalker = = RussellTerrierRussellTerrier (( "Johnny Walker""Johnny Walker" , , 44 ) ) printprint (( isinstanceisinstance (( johnnywalkerjohnnywalker , , BulldogBulldog ))))# is julie and instance of jim? # is julie and instance of jim? printprint (( isinstanceisinstance (( juliejulie , , jimjim )) ))

Output:

輸出:

Make sense? Both jim and julie are instances of the Dog() class, while johnnywalker is not an instance of the Bulldog() class. Then as a sanity check, we tested if julie is an instance of jim, which is impossible since jim is an instance of a class rather than a class itself—hence the reason for the TypeError.

合理? jim和julie都是Dog()類的實例,而johnnywalker則不是Bulldog()類的實例。 然后,作為健全性檢查,我們測試了julie是否是jim的實例,這是不可能的,因為jim是一個類的instance ,而不是一個類本身-因此,發生TypeError的原因。

覆蓋父類的功能 (Overriding the Functionality of a Parent Class)

Remember that child classes can also override attributes and behaviors from the parent class. For examples:

請記住,子類也可以覆蓋父類的屬性和行為。 舉些例子:

>>> >>> class class DogDog (( objectobject ): ): ... ... species species = = 'mammal' 'mammal' ... ... >>> >>> class class SomeBreedSomeBreed (( DogDog ): ): ... ... pass pass ... ... >>> >>> class class SomeOtherBreedSomeOtherBreed (( DogDog ): ): ... ... species species = = 'reptile' 'reptile' ... ... >>> >>> frank frank = = SomeBreedSomeBreed () () >>> >>> frankfrank .. species species 'mammal' 'mammal' >>> >>> beans beans = = SomeOtherBreedSomeOtherBreed () () >>> >>> beansbeans .. species species 'reptile' 'reptile'

The SomeBreed() class inherits the species from the parent class, while the SomeOtherBreed() class overrides the species, setting it to reptile.

SomeBreed()類從父類繼承該species ,而SomeOtherBreed()類覆蓋該species ,將其設置為reptile 。

復習練習(#2) (Review Exercises (#2))

“Dog Inheritance” Show/Hide

“狗的繼承” 顯示/隱藏

Create a Pet() class that holds instances of dogs; this class is completely separate from the Dog() class. In other words, the Dog() class does not inherit from the Pet() class. Then assign three dog instances to the Pet() class. Start with the following code below. Save the file as pet_class.py. Your output should look like this:

創建一個Pet()類來保存狗的實例; 該類與Dog()類完全分開。 換句話說, Dog()類不會從Pet()類繼承。 然后將三個狗實例分配給Pet()類。 從下面的以下代碼開始。 將文件另存為pet_class.py。 您的輸出應如下所示:

Starter code:

入門代碼:

# Parent class # Parent class class class DogDog (( objectobject ):):# Class attribute# Class attributespecies species = = 'mammal''mammal'# Initializer / Instance attributes# Initializer / Instance attributesdef def __init____init__ (( selfself , , namename , , ageage ):):selfself .. name name = = namenameselfself .. age age = = ageage# instance method# instance methoddef def descriptiondescription (( selfself ):):return return "{} is {} years old""{} is {} years old" .. formatformat (( selfself .. namename , , selfself .. ageage ))# instance method# instance methoddef def speakspeak (( selfself , , soundsound ):):return return "{} says {}""{} says {}" .. formatformat (( selfself .. namename , , soundsound ))# child class (inherits from Dog() class) # child class (inherits from Dog() class) class class RussellTerrierRussellTerrier (( DogDog ):):def def runrun (( selfself , , speedspeed ):):return return "{} runs {}""{} runs {}" .. formatformat (( selfself .. namename , , speedspeed ))# child class (inherits from Dog() class) # child class (inherits from Dog() class) class class BulldogBulldog (( DogDog ):):def def runrun (( selfself , , speedspeed ):):return return "{} runs {}""{} runs {}" .. formatformat (( selfself .. namename , , speedspeed ) )

“Hungry Dogs” Show/Hide

“餓狗” 節目/隱藏

Using the same file, add a class attribute of is_hungry = True to the Dog() class. Then add a method called eat() which changes the value of is_hungry to False when called. Figure out the best way to feed each dog and then output “My dogs are hungry.” if all are hungry or “My dogs are not hungry.” if all are not hungry. The final output should look like this:

使用同一文件,將is_hungry = True的類屬性添加到Dog()類。 然后添加一個名為eat()的方法,該方法在調用時將is_hungry的值更改為False 。 找出喂養每只狗的最佳方法,然后輸出“我的狗餓了”。 如果所有人都餓了或“我的狗不餓”。 如果都不餓 最終輸出應如下所示:

“Dog Walking” Show/Hide

“狗走路” 顯示/隱藏

Next, add a walk() method to both the Pet() and Dog() classes so that when you call the method on the Pet() class, each dog instance assigned to the Pet() class will walk(). Save this as dog_walking.py. This is slightly more difficult.

接下來,添加一個walk()方法將兩個Pet()和Dog()類,這樣當你調用該方法在Pet()類,分配給每條狗實例Pet()類將walk() 將其另存為dog_walking.py。 這有點困難。

Start by implementing the method in the same manner as the speak() method. As for the method in the Pet() class, you will need to iterate through the list of dogs, then call the method itself.

首先以與speak()方法相同的方式實現該方法。 至于Pet()類中的方法,您將需要遍歷狗列表,然后調用方法本身。

The output should look like this:

輸出應如下所示:

Tom is walking! Mike is walking! Larry is walking! Tom is walking! Mike is walking! Larry is walking!

“Comprehension Check” Show/Hide

“綜合檢查” 顯示/隱藏

Answer the following questions about OOP to check your learning progress:

回答有關OOP的以下問題,以檢查您的學習進度:

  • What’s a class?
  • What’s an instance?
  • What’s the relationship between a class and an instance?
  • What’s the Python syntax used for defining a new class?
  • What’s the spelling convention for a class name?
  • How do you instantiate, or create an instance of, a class?
  • How do you access the attributes and behaviors of a class instance?
  • What’s a method?
  • What’s the purpose of self?
  • What’s the purpose of the __init__ method?
  • Describe how inheritance helps prevent code duplication.
  • Can child classes override properties of their parents?
  • 什么課?
  • 什么是實例?
  • 類和實例之間有什么關系?
  • 用于定義新類的Python語法是什么?
  • 類名的拼寫約定是什么?
  • 您如何實例化類或創建類的實例?
  • 您如何訪問類實例的屬性和行為?
  • 有什么方法?
  • self的目的是什么?
  • __init__方法的目的是什么?
  • 描述繼承如何幫助防止代碼重復。
  • 子類別可以覆蓋其父母的屬性嗎?
  • 結論 (Conclusion)

    You should now know what classes are, why you would want or need to use them, and how to create both parent and child classes to better structure your programs.

    現在,您應該知道什么是類,為什么要使用或需要使用它們,以及如何創建父類和子類以更好地構造程序。

    Please be aware that OOP is a programming paradigm and not a Python concept. Most of the modern programming languages such as Java, C#, C++ follow OOP principles. So the good news is that learning object-oriented programming fundamentals will be valuable to you in a variety of circumstances—whether you’re working in Python or not.

    請注意,OOP是編程范例,而不是Python概念。 Java,C#,C ++等大多數現代編程語言都遵循OOP原則。 因此,好消息是,無論您是否在Python中工作,學習面向對象的編程基礎知識在各種情況下對您來說都是有價值的。

    For further explanation of objected-oriented programming in Python, we recommend that you consult these additional resources:

    有關Python中面向對象編程的進一步說明,建議您參考以下其他資源:

    Free Bonus: Click here to get access to a free Python OOP Cheat Sheet that points you to the best tutorials, videos, and books to learn more about Object-Oriented Programming with Python.

    免費獎金: 單擊此處可獲取免費的Python OOP作弊表 ,該指南將為您提供最佳的教程,視頻和書籍,以了解有關使用Python進行面向對象編程的更多信息。

    翻譯自: https://www.pybloggers.com/2018/02/object-oriented-programming-oop-in-python-3/

    python oop編程

    總結

    以上是生活随笔為你收集整理的python oop编程_Python 3中的面向对象编程(OOP)的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。