9.1 Create and use classes

9.1.1 establish Dog class

   according to Dog Each instance created by the class will store the name and age , We gave each dog a squat (sit( )) And roll (roll_over( )) The ability of :

class Dog:
""" A simple attempt to simulate a puppy """ def __init__(self, name, age):
""" Initialization property name and age."""
self.name = name
self.age = age def sit(self):
""" Simulate the dog squatting down after receiving the order """
print(f'{self.name} is now sitting.') def roll_over(self):
""" Simulate a dog rolling when ordered ."""
print(f"{self.name} roll over!")

   Method __init__()

   A function in a class is called a method . Everything you learned about functions earlier applies to methods , For now , The only important difference is the way the method is called . The first 4 The way to go __init__() It's a special method , Every time you look at Dog Class when a new instance is created , Python Will run it automatically .

   In the name of the method , There are two underscores at the beginning and the end , It's a convention , To avoid Python The default method has a name conflict with the normal method . Make sure that __init__() On both sides of the Two Underline , Otherwise, when you use classes to create instances , This method will not be called automatically , Which leads to hard to find errors .

   We're going to approach __init__() Defined as containing three formal parameters :self、name and age. In the definition of this method , Shape parameter self essential , And must In front of other formal parameters .

   Why must form parameters be included in the method definition self Well ? because Python Call this method to create Dog When an instance , Arguments are automatically passed in self. Each method call associated with an instance automatically passes arguments self, It is a reference to the instance itself , Gives instances access to properties and methods in the class .

   establish Dog When an instance ,Python Will call Dog Class method __init__(). We're going to go through the argument direction Dog() Pass the name and age ,self It will automatically pass , So there's no need to pass it on . Whenever according to Dog Class when an instance is created , I'm just going to give you the last two parameters (name and age) Provide value .

   attribute

   The first 4 Both variables defined at line have prefixes self. With self Variables prefixed with are available to all methods in the class , Can be accessed through any instance of the class .self.name=name Get and formal parameters name Associated value , And assign it to a variable name, This variable is then associated with the currently created instance .self.age=age The effect is similar .

   Variables that can be accessed through instances like this are called attribute .

  Dog The class also defines two other methods :sit() and roll_over(). These methods do not require additional information to execute , So they only have one parameter self.

9.1.2 Create an instance based on the class

   Create an instance that represents a particular dog :

my_dog = Dog('Willie', 6)
print(f"My dog's name is {my_dog.name}.")
print(f"My dog is {my_dog.age} years old.")

output:

My dog's name is Willie.

My dog is 6 years old.

   The first 1 That's ok , Give Way Python Create a name of 'Willie', Age is 6 The little dog .

   When I run into this line of code ,Python Using the arguments 'Willie' and 6 call Dog Class method __init__(). Method __init__() Create an instance that represents a particular dog , And use the provided value to set the property name and age.

   Next ,Python Returns an instance representing the dog , And we assign this instance to the variable my_dog. ad locum , Naming conventions are useful : Names that can usually be considered capitalized ( Such as Dog) Refers to the class , Lower case names ( Such as my_dog) Refers to an instance created from a class .

  a. Access properties —— Period notation

   The properties of the instance to access , Period notation can be used .

   Period notation Python In the common , This syntax is demonstrated Python How do I know the value of an attribute . ad locum ,Python Find the instance first my_dog, Then find the attribute associated with the instance name.

   stay Dog When this property is referenced in a class , It uses self.name and self.age.

  b. Calling method

   according to Dog Class after the instance is created , You can use the period notation to call Dog Any method defined in the class .

   Let's make the dog squat and roll :

my_dog.sit()
my_dog.roll_over()

output:

Willie is now sitting.

Willie roll over!

   To invoke a method , The name of the instance can be specified ( Here is my_dog) And the method to call , And separated by a period .

   Meet the code my_dog.sit() when ,Python In the class Dog Find method in sit() And run the code .Python Interpret the code in the same way my_dog.roll_over().

   As we can see, the output ——Willie Did as we ordered .

  c. Create multiple instances

my_dog = Dog('Willie', 6)
your_dog = Dog('Lucy', 3)
print(f"My dog's name is {my_dog.name}.")
print(f"My dog is {my_dog.age} years old.")
my_dog.sit()
print(f"\nYour dog's name is {your_dog.name}.")
print(f"Your dog is {your_dog.age} years old.")
your_dog.sit()

output:

My dog's name is Willie.

My dog is 6 years old.

Willie is now sitting.

Your dog's name is Lucy.

Your dog is 3 years old.

Lucy is now sitting.

   In this example, two puppies are created , Respectively called Willie and Lucy. Every dog is a separate instance , It has its own set of attributes , Be able to perform the same operation .

   Even if the second puppy is given the same name and age ,Python Will still be based on Dog Class creates another instance . You can create as many instances of a class as you want , The condition is that each instance is stored in a different variable , Or occupy different places in a list or dictionary .

Exercises

Create a file called Restaurant Class , For its method __init__() Set properties restaurant_name and cuisine_type.

Create a file called describe_restaurant() And a method called open_restaurant() Methods , The former prints the above two information , The latter prints a message , Point out that the restaurant is open .

Create a class named restaurant Example , Print its two properties separately , Then call the above two methods .

Python book learning notes ——Chapter 09 Section 01 More articles about creating and using classes

  1. Puppet Learning notes (CentOS6.3+Puppet3.01)

    Puppet Learning notes (CentOS6.3+Puppet3.01)   technology  Add comments Oct262012 Determined , study hard puppet, Go to a special weekend puppet Training , Rare friends ...

  2. Directx11 Learning notes 【 Two 】 take HelloWin Encapsulation into classes

    We encapsulate the code from the previous tutorial into a class to facilitate future use . First, build a new project called MyHelloWin, Add one main.cpp file , Then create a new class called MyWindow, Encapsulate the operations related to the form My ...

  3. golang Learning notes 5 use bee Tools to create projects bee Tool introduction

    golang Learning notes 5 use bee Tools to create projects bee Tool introduction Bee Tool use - beego: Simplicity & Strong and powerful Go Application framework https://beego.me/docs/instal ...

  4. Android Learning notes ——Activity Start and create

    http://www.cnblogs.com/bastard/archive/2012/04/07/2436262.html Android Activity Learning notes ——Activity Start and create ...

  5. WPF Learning notes - stay WPF Create a tray icon under

    original text :WPF Learning notes - stay WPF Create a tray icon under First, you need to quote System.Windows.Forms,System.Drawing; using System; using System.Co ...

  6. Set sail again , One of my study notes JavaScript Design patterns 01

    My study notes are updated regularly according to my study situation , expect 2-3 Day update a chapter , Mainly to share with you , What I learned , If there are any mistakes, please point them out in the comments , I will accept it with an open mind , Let's start today's learning and sharing ! Zaitong ...

  7. 0025 Java Learning notes - object-oriented -final Modifier 、 Immutable classes

    final Where can keywords be used decorator : This class is not inheritable Modifying variables : This variable cannot be reassigned once it is initialized , Even if the value is the same as the initialized value or points to the same object , You can't either Class variables : Instance variables : Shape parameter : Note that you can modify formal parameters ...

  8. Dynamic CRM 2013 Learning notes ( 3、 ... and ) Create entities quickly EntityCreater

    One . Entity profile Entities are used in Microsoft Dynamics CRM Establish business data model and manage business data . for example , You can use customer . Marketing activities and events ( Case study ) And other entities to track and support sales . Marketing and service activities . The entity has a ...

  9. Android(java) Learning notes 167:Java Class introduction of operation file in (File + IO flow )

    1.File class : Class that operates on files and directories on the hard disk .    File Class is an abstract representation of file and directory pathnames   Constructors :        1) File(String pathname)       Creat ...

  10. C++ Learning notes 47: The concept of linked list and node class template

    School online learning notes The concept of linked list and node class template Linear groups of sequential access -- List class Linked list is a kind of dynamic data structure , Can be used to represent linear groups of sequential access : A linked list consists of a series of nodes , Nodes can be generated dynamically at run time : Each node includes a data field ...

Random recommendation

  1. Android Use in AsyncTask Realize file download and progress update prompt

    Android A tool class is provided :AsyncTask, It makes it easier to create long-running tasks that need to interact with the user interface . relative Handler Come on AsyncTask More lightweight , For simple asynchronous processing , No need to use threads and ...

  2. Cattle pen (vijos 1054)

    The main idea of the topic : give N Seed stick ( The number of sticks of each kind is unlimited ) The length of (<=3000), Each stick can cut it off [1,M] To get a new stick .  Find the maximum length that cannot be combined .  If any length can be combined or the maximum value is not up ...

  3. angularJs $injector

    One angularJS Several injection methods in Spring Structure injection or set value injection is used in , Some additional operations are needed , however angular You only need to declare it where you need it , References to similar modules , So it's very convenient . angu ...

  4. shell Check the process

    use shell The script monitors whether the process exists If not, start the instance , Code dry first : #!/bin/shps -fe|grep processString |grep -v grepif [ $? -ne 0 ]th ...

  5. iOS Alipay payment for integrated payment development

    The payment function should be used in the project , Alipay is needed. , WeChat , Three major payments of UnionPay , So I'm going to summarize , Write two articles , Convenient for future reference , We can also make a little reference when we do it , The place to be used should be avoided to be pit again . This is the second Alipay integration. , The first UnionPay payment is here . ...

  6. LeetCode 171 Excel Sheet Column Number Problem solving report

    Subject requirements Given a column title as appear in an Excel sheet, return its corresponding column number. For e ...

  7. [Aaronyang Purple blog ] Write to yourself WPF4.5-Blend5 Open class series 2- Further more

      My article must be responsible to the readers , Otherwise, it will be a failed article  ---------   www.ayjs.net    aaronyang Technology sharing Welcome to support my masterpiece <[Aaronyang] Write to yourself ...

  8. Eclipse export WAR package

    Reference resources : https://jingyan.baidu.com/article/ab0b56309110b4c15afa7de2.html

  9. AVR Naming rules of single chip microcomputer

    ATmega64 TQFP There are mainly the following models of packaging :ATmega64L-8AU.ATmega64L-8AI.ATmega64-16AU.ATmega64-16AI. Model identification description : (1) belt "L ...

  10. ElasticSearch Actual combat summary

    Recently, Sino US relations have become increasingly tense , The domestic economy is declining , The stock market is gloomy , The Internet industry is more and more depressed , At any time, the market value has fallen by hundreds of billions , Write some documents to comfort this injured heart ... With the development of the Internet , Data is more and more important , The data saved by each company is also more ...