python oop编程

您所在的位置:网站首页 p6ke18ca二极管参数 python oop编程

python oop编程

2023-10-07 08:54| 来源: 网络整理| 查看: 265

python oop编程

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

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

Python ClassesObject InstancesDefining and Working with MethodsOOP 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 Attribute species species = = 'mammal' 'mammal' # Initializer / Instance Attributes # Initializer / Instance Attributes def def __init____init__ (( selfself , , namename , , ageage ): ): selfself .. name name = = name name selfself .. 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 ) )

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”

“最老的狗”

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 Attribute species species = = 'mammal' 'mammal' # Initializer / Instance Attributes # Initializer / Instance Attributes def def __init____init__ (( selfself , , namename , , ageage ): ): selfself .. name name = = name name selfself .. age age = = age age # instance method # instance method def def descriptiondescription (( selfself ): ): return return "{} is {} years old""{} is {} years old" .. formatformat (( selfself .. namename , , selfself .. ageage ) ) # instance method # instance method def 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 attribute species species = = 'mammal' 'mammal' # Initializer / Instance attributes # Initializer / Instance attributes def def __init____init__ (( selfself , , namename , , ageage ): ): selfself .. name name = = name name selfself .. age age = = age age # instance method # instance method def def descriptiondescription (( selfself ): ): return return "{} is {} years old""{} is {} years old" .. formatformat (( selfself .. namename , , selfself .. ageage ) ) # instance method # instance method def 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 attribute species species = = 'mammal' 'mammal' # Initializer / Instance attributes # Initializer / Instance attributes def def __init____init__ (( selfself , , namename , , ageage ): ): selfself .. name name = = name name selfself .. age age = = age age # instance method # instance method def def descriptiondescription (( selfself ): ): return return "{} is {} years old""{} is {} years old" .. formatformat (( selfself .. namename , , selfself .. ageage ) ) # instance method # instance method def 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”

“狗的继承”

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 attribute species species = = 'mammal' 'mammal' # Initializer / Instance attributes # Initializer / Instance attributes def def __init____init__ (( selfself , , namename , , ageage ): ): selfself .. name name = = name name selfself .. age age = = age age # instance method # instance method def def descriptiondescription (( selfself ): ): return return "{} is {} years old""{} is {} years old" .. formatformat (( selfself .. namename , , selfself .. ageage ) ) # instance method # instance method def 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”

“饿狗”

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”

“狗走路”

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”

“综合检查”

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编程



【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3