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 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 )
)
<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”

“最老的狗”

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的以下问题,以检查您的学习进度:

  1. What’s a class?
  2. What’s an instance?
  3. What’s the relationship between a class and an instance?
  4. What’s the Python syntax used for defining a new class?
  5. What’s the spelling convention for a class name?
  6. How do you instantiate, or create an instance of, a class?
  7. How do you access the attributes and behaviors of a class instance?
  8. What’s a method?
  9. What’s the purpose of self?
  10. What’s the purpose of the __init__ method?
  11. Describe how inheritance helps prevent code duplication.
  12. Can child classes override properties of their parents?
  1. 什么课?
  2. 什么是实例?
  3. 类和实例之间有什么关系?
  4. 用于定义新类的Python语法是什么?
  5. 类名的拼写约定是什么?
  6. 您如何实例化类或创建类的实例?
  7. 您如何访问类实例的属性和行为?
  8. 有什么方法?
  9. self的目的是什么?
  10. __init__方法的目的是什么?
  11. 描述继承如何帮助防止代码重复。
  12. 子类别可以覆盖其父母的属性吗?

结论 (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编程

C#串口通信革命:RJCP.DLL.SerialPortStream实战全解析 本文介绍了如何通过RJCP.DLL.SerialPortStream库实现高性能串口通信解决方案。相比.NET自带的SerialPort类,该库提供了完全的异步非阻塞IO、动态缓冲区控制和多线程事件驱动等优势,特别适合工业自动化和物联网场景。文章详细讲解了环境搭建、核心功能对比,并通过代码示例展示了端口配置、异步通信管道搭建等关键技术。最后以Modbus RTU协议为例,演示了高级协议封装方法,为开发者提供了完整的工业级串口通信实现方案。 阅读详情

相关推荐

从流体力学到深度学习:手把手教你用PINN预测涡流场(基于TensorFlow2.10+GPU)

本文详细介绍了如何利用物理信息神经网络(PINN)结合TensorFlow 2.10和GPU加速,预测Navier-Stokes方程的涡流场。通过核心原理讲解、实战环境配置、网络架构设计及物理约束实现,帮助读者掌握从流体力学到深度学习的跨学科技术应用,特别适合处理复杂流体问题和非定常流动场景。

weixin_29048309的博客 220

28.Python从入门到精通—Python3 面向对象 面向对象技术简介 类定义 类对象 类的方法

面向对象编程(Object-Oriented Programming,OOP)是一种编程范式,它将现实世界中的事物抽象为对象,通过对象之间的交互实现程序的设计和实现。面向对象编程是一种强大的编程模型,它可以提高程序的可维护性、可重用性和可扩展性。在面向对象编程中,一个对象是一个实例,它包含有状态和行为。状态是对象的属性,行为是对象的方法。对象之间可以通过消息传递来相互交互,从而实现程序的功能。封装(Encapsulation):封装是指将对象的状态和行为封装在一起,通过接口来隐藏对象的实现细节。

weixin_50804299的博客 5506

Oracle 19c RAC安装踩坑实录:OpenSSH 8.x版本与OUI的“兼容性战争”及一劳永逸的解决思路

本文深入解析Oracle 19c RAC在Linux8环境中部署时遇到的OpenSSH 8.x版本兼容性问题,特别是[INS-06006]错误的根源与解决方案。从协议层分析冲突本质,提供SCP包装器技术、官方补丁应用指南及现代化部署体系构建三种解决方案,帮助企业高效完成RAC安装并规避类似问题。

weixin_42648844的博客 461

【Python】 面向对象:输出年龄最大的对象所对应的名字

问题:用相同的Dog类,实例化三只新狗,每只狗的年龄不同。然后编写一个名为get_biggest_number()的函数,它接受任意数量的年龄并返回最旧的函数。然后输出最老的狗的年龄. class Dog: # Class Attributes species = 'mammal' # Initializer /Instance Attributes ...

GreatcloudL的博客 1775

从零构建:用Simulink搭建固定翼无人机六自由度模型的避坑指南

本文详细介绍了使用Simulink从零构建固定翼无人机六自由度动力学模型的完整流程和避坑指南。重点解析了模型架构设计、气动力计算、参数配置、仿真求解器选择等关键环节的常见问题与解决方案,帮助开发者快速建立准确可靠的无人机控制系统仿真模型。

hhh00的博客 1007

YOLOv10注意力革新:小波域注意力(WDA)如何实现多尺度特征精准聚焦

本文深入解析YOLOv10中的小波域注意力(WDA)机制,探讨其如何通过频域分解与动态聚焦实现多尺度特征精准提取。WDA模块结合离散小波变换与注意力机制,显著提升小目标检测性能,在VisDrone数据集上AP提升达12.6%。文章详细介绍了两种集成方案及代码实现,为计算机视觉开发者提供实用指南。

weixin_29079671的博客 258

骆驼拼写法(CamelCase)

在英语中,依靠单词的大小写拼写复合词的做法,叫做"骆驼拼写法"(CamelCase)。比如,backColor这个复合词,color的第一个字母采用大写。 这种拼写法在正规的英语中是不允许的,但是在编程语言和商业活动中却大量使用。比如,sony公司的畅销游戏机PlayStation,play和station两个词的词首字母都是大写的。 它之所以被叫做"骆驼拼写法",是因为大小写的区分使得复合词

学习笔记 3196

高质量水下垃圾数据集解析与应用实践

计算机视觉在环保领域的应用日益广泛,其中目标检测技术是关键支撑。通过深度学习模型对水下垃圾进行精准识别,需要高质量标注数据集作为基础。1962幅水下垃圾数据集采用专业预处理流程,包括色彩校正、去雾增强等技术,有效解决了水下图像的光照不均、水体浑浊等典型问题。该数据集覆盖12类常见海洋垃圾,标注错误率低于2%,显著提升了模型训练效果。在工程实践中,该数据集特别适合用于水下机器人实时检测系统和海洋垃圾分布热力图生成等场景,通过优化模型架构和数据增强策略,可实现更高效的环境监测与保护。

weixin_42616115的博客 258

什么是面向对象编程?OOP 深入解释

面向对象编程 (OOP) 是一种基本的编程范式,几乎每个开发人员都在其职业生涯的某个阶段使用过。OOP 是用于软件开发的最流行的编程范例,并且在大多数程序员的教育生涯中被作为标准编码方式教授。 另一种流行的编程范式是函数式编程,但我们现在不讨论它。 今天,我们将分解使程序面向对象的基础知识,以便您可以开始在您的算法、项目和面试中使用这种范式。 现在,让我们深入了解这些 OOP 概念和教程! ...

qq_37116560的博客 5185

基于STM32L4XX、HAL库的ESP32-S3-WROOM-1-N4 WIFI模块驱动程序设计

/ 检查是否收到完整的一行(以\r\n结尾)// 例如: 解析AT命令响应或MQTT消息等。// UART2初始化已在CubeMX中配置。// USART2初始化函数(由CubeMX生成)// 缓冲区溢出,重置。// 如果需要等待响应。// 处理接收到的数据。// 处理接收到的数据。// 等待ESP32模块启动。// 主循环其他任务。// 启用UART全局中断。// 发送HTTP GET请求。// 发送AT测试命令。// 连接Wi-Fi。// UART中断回调函数。

zhusl6688的博客 294

S7-1200PLC V90伺服绝对值编码器校准功能块

S7-1200PLC通过111报文和EPOS模式实现位置轴轴控功能(FB284封装)-CSDN博客文章浏览阅读173次。EASY_SINA_POS的详细使用介绍请参考下面文章链接:S7-1200PLC使用标准报文111和EPOS模式实现V90 PN总线伺服定位(Easy_SINA_Pos)_西门子sinapos-CSDN博客文章浏览阅读132次。文章浏览阅读7k次。先简单说下如何获取FB284,一般有2种方法,Startdrive软件可以操作大部分西门子的驱动器,建议安装调试方便,缺点就是软件太大。

RXXW_Dor的博客 970

python3——面向对象oop

方法的定义格式和之前学习过的函数的定义几乎一样区别在于第一个参数必须是self在日常开发中,不推荐在类的外部给对象增加属性如果在运行时,没有找到属性,程序会报错对象应该包含有哪些属性,应该封装在类的内部当使用类名()创建对象时,会自动为对象在内存中分配空间—— 创建对象为对象的属性设置初始值—— 初始化方法(init这个初始化方法就是__init__方法,__init__是对象的内置方法__init__方法是专门用来定义一个类具有哪些属性的方法!在BearToy中增加__init__

qq_44864681的博客 213

零基础入门simulink建模仿真--基于Simulink的QPSK调制与解调仿真建模示例

QPSK是一种相位调制技术,将两个比特映射到一个符号上,每个符号对应四个可能的相位之一(0°、90°、180°、270°)。通过Simulink,我们可以通过模块化的建模方式实现QPSK的调制和解调过程,并观察信号在信道中的传输效果。通过本指南,我们介绍了如何基于Simulink搭建一个完整的QPSK调制与解调仿真模型,并进行仿真和性能评估。背景介绍:理解QPSK调制与解调的基本原理及其应用。所需工具和环境:列出进行QPSK仿真所需的工具和环境。步骤详解。

amy_mhd的博客 1313

python3 oop面向对象编程入门

class Beartoy: #新建一个类 def __init__(self, name, size, color): #定义方法,用于创建实例用 self.name = name self.size = size self.color = color if __name__ == '__main__': b1 = Beartoy('Tidy'.

walk on the road of linux 336

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

Python 3 面向对象编程 (OOP):全景指南

Python 3 面向对象编程(OOP)全景指南 面向对象编程是Python的核心范式,从Python 2.2引入新式类到Python 3的彻底统一,OOP通过封装、继承、多态三大特性成为构建复杂系统的基石。本文系统介绍了Python OOP的发展历程、核心概念与语法结构,包括类与对象、类变量与实例变量、方法类型、继承与重写、特殊方法等关键知识点。特别针对常见陷阱如可变对象作为类变量、忘记self参数、混淆变量作用域等提供了避坑指南。

独坐一隅,凝神遐想,是种幸福! —— 独隅 713

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

Python3 OOP面向对象编程最基本的类

小米路由器出了问题告别了一天网络,也不知道是出了什么问题。真有些怀疑被黑了,用了一年的密码居然怎么也不好用了。把路由器恢复了出厂设置又把密码彻底更新了一遍。由于网络折腾,都两天没有好好学习了。       最近开始深入学习Python OOP,当然,目前还是一个起步的阶段。我觉得面向对象编程的技术我肯定要学,最好的选择或许是Python、Java、C#中的一个。前面了解了一下MATLAB面向对象

小灰笔记 1020

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

Python3基础:08_01_面向对象编程(OOP)——面向对象编程的概念

这篇博文将介绍面向对象编程的特点以及面对对象技术的简介。

Jacks丶的博客 793

Python3.6基础知识--面向对象编程OOP 在PyCharm终端使用conda命令新建添加虚拟环境

没错,Python也是面向对象编程的一门语言,面向对象编程简称是OOP,是目前主流的编程思想;它是相对于面向过程发展出来的一个编程思想,了解OOP之前,先看下什么叫面向过程 面向过程就是分析出解决问题所需要的步骤,然后用函数把这些步骤一步一步实现,使用的时候一个一个依次调用就可以了 而面向对象是把构成问题事物分解成各个对象,建立对象的目的不是为了完成一个步骤,而是为了描叙某个事物在整个解决问题的步骤中的行为

Mango先生的博客 2929

【Python面试笔记】3.3.1 面向对象编程(OOP)继承 父类与子类

继承是面向对象编程的核心概念之一,通过继承,我们可以让子类共享父类的属性和方法,减少代码重复,同时提高代码的可维护性;通过方法重写和super(),我们可以在子类中扩展和修改父类的行为,实现更灵活的功能。

m0_64866459的博客 383

Python3的面向对象编程

Python3的面向对象编程 面向对象OOP 全称Object Oriented Programming 对象作为基本单元,将数据和功能封装在里面. 实现很好的,复用性,灵活性扩展性. 面向对象的概念 面向对象时一种抽象 这里的抽象指的是,用分类的眼光看待事物的一种方法. 对一些事物进...

chuanguan1820的博客 260

【Python面试笔记】3.3.2 面向对象编程(OOP)继承 方法重写

继承允许子类复用父类的代码,子类可以添加新的属性和方法,也可以重写父类的方法方法重写允许子类提供自己对继承方法的实现,改变父类方法的行为super()函数可以在子类中调用父类的构造方法或其他方法,确保继承关系中的父类功能不被完全覆盖继承和方法重写是面向对象编程中非常重要的特性,它们增强了代码的可复用性和可扩展性。

m0_64866459的博客 221

【Python面试笔记】3.1.3 面向对象编程(OOP)类和对象 实例化

Python 是一门支持面向对象编程(OOP)的语言;面向对象编程通过将数据和操作数据的功能(方法)封装到一个单位中,帮助程序员管理和组织代码;OOP的核心概念包括类(Class)、对象(Object)、实例化(Instantiation)、继承(Inheritance)、封装(Encapsulation)和多态(Polymorphism)Dog类(Class)是对象的模板或蓝图,它定义了对象的属性和行为对象(Object)是类的实例,通过实例化类来创建对象;对象保存了类中定义的数据和方法。

m0_64866459的博客 456

【Python面试笔记】3.3.3 面向对象编程(OOP)继承 super()调用父类方法

继承是面向对象编程的核心特性之一,允许子类继承父类的方法和属性super()用于在子类中调用父类的方法,尤其在方法重写时非常有用在多重继承中,super()遵循MRO规则,按照方法解析顺序调用父类的方法通过super()的合理使用,能够更有效地管理继承关系,尤其是在复杂的多重继承场景下,确保父类的方法能按照预期的顺序被调用。

m0_64866459的博客 407

Python3基础:08_02_面向对象编程(OOP)——类和对象

这篇博文将讲述Python面向对象开发中的类与对象的概念,包括对类和对象的理解,类和对象的关系以及类和对象的创建。

Jacks丶的博客 716

【Python面试笔记】3.2.3 面向对象编程(OOP)属性与方法 静态方法

在Python的面向对象编程(OOP)中,类的和是核心概念,它们使得对象能够具有状态(属性)和行为(方法);以下是以及。

m0_64866459的博客 328

Python3基础:08_04_面向对象编程(OOP)——单继承和多继承

这篇博客主要介绍Python面向对象编程中的继承概念以及继承中的相关语法和注意事项。

Jacks丶的博客 694
上一篇: 投篮 lock_创建NBA投篮图表
下一篇: TrialHandler – PsychoPy教程
cumei1658
博客等级 码龄11年 91粉丝 0原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址