To create an instance of a simple class tutorial

Source: Internet
Author: User

To create a simple class

Each real column created by the dog class stores the name and age. We have given each puppy the ability to squat (sit ()) and Roll (Roll_over ()):

1 Class Dog (): 2     "" "A simple attempt at simulating a puppy" "3     def __init__ (self, Name, age): 4" ""         initialization property name and age "" "5         self.name = n Ame 6         self.age = age 7     def sit (self): 8         "" "simulated puppies are ordered to squat" "" "9         Print (Self.name.title () +" now is sitting. ") Ten     def roll_over (self): one         "" "Simulated puppy rolls when ordered" "" "         Print (Self.name.title () +" rolled over! ") My_dog = Dog (' Tom ', ' 3 ') print ("My dog name is" + my_dog.name.title ())
According to the Convention, in Python, the first capitalization name refers to a class: A function in a class is called a method method __init__ (), with 2 underscores at the beginning and the end, which is a convention designed to avoid conflicts between the Python default method and the common method name. we will approach __init__ () selfnameageselfselfpython call this __init__ () method to create dog instance, will automatically pass in the argument self in Python2. X, if you create the class you need to add (object) after the parentheses.

Accessing properties

Continuing with the example above, Method __init__ () Creates an example that represents a particular puppy and sets the property name and age using the values we provide, the method __init__ () does not explicitly include the return statement, but Python automatically returns an example that represents the puppy. We will store this example in the variable My_dog.
Class Dog (): "" "a simple attempt at simulating a puppy" "" "Def __init__ (self, Name, age):" "Initialize property name and age" "" Self.name = name        Self.age = agedef Sit (self): "" "The simulation puppy is ordered to squat" "" "Print (Self.name.title () +" now is sitting. ") def roll_over (self): "" "Simulate Puppy Roll" "" Print (Self.name.title () + "rolled over!") when ordered My_dog = Dog (' Tom ', 3) print (my_dog.name) print (my_dog.age) #运行结果tom3

Calling methods

Class Dog (): "" "a simple attempt at simulating a puppy" "" "Def __init__ (self, Name, age):" "Initialize property name and age" "" Self.name = name        Self.age = agedef Sit (self): "" "The simulation puppy is ordered to squat" "" "Print (Self.name.title () +" now is sitting. ") def roll_over (self): "" "Simulate Puppy Roll" "" Print (Self.name.title () + "rolled over!") when ordered My_dog = Dog (' Tom ', 3) my_dog.sit () My_dog.roll_over () #运行结果Tom now is sitting. Tom rolled over!

After you create an instance from the dog class, you can use a period representation to call any method defined by the dog

Create multiple instances

Class Dog (): "" "a simple attempt at simulating a puppy" "" "Def __init__ (self, Name, age):" "Initialize property name and age" "" Self.name = name        Self.age = agedef Sit (self): "" "The simulation puppy is ordered to squat" "" "Print (Self.name.title () +" now is sitting. ") def roll_over (self): "" "Simulate Puppy Roll" "" Print (Self.name.title () + "rolled over!") when ordered My_dog = Dog (' Tom ', 3) Your_dog = Dog (' Mei ', 2) print ("My dog name is" + my_dog.name.title ()) print ("Your dog name is" + your _dog.name.title ()) #运行结果My dog name is Tomyour dog name is Mei

You can create as many instances as you want based on your class.

Working with classes and instances

Assigning a default value to a property

Each property in a class must have an initial value, even if the value is 0 or an empty string, in some cases, such as when setting a default value, it is possible to specify such an initial value within method __init__ () No, if you do this to a property, you do not need to include the formal parameter that provides initialization for him.
Class car (): "" "a simple attempt to simulate a car" "Def __init__ (self, make, model, year):" "The initialization of the car" "" Self.make = make        Self.model = model< C1/>self.year = year        self.odometer_reading = 100def get_descri_name (self): "" "Description Car" "" long_name = str (self.year) + " + Self.model + ' + self.makereturn Long_namemy_car = car (' Audi ', ' A4 ', ') ' Print (My_car.model) print (MY_CAR.GET_DESCR I_name ()) #运行结果a42017 A4 Audi

Directly modify the value of a property

Class car (): "" "a simple attempt to simulate a car" "Def __init__ (self, make, model, year):" "The initialization of the car" "" Self.make = make        Self.model = model< C1/>self.year = year        self.odometer_reading = 100def get_descri_name (self): "" "Description Car" "" long_name = str (self.year) + " + Self.model + ' + self.makereturn Long_namemy_car = car (' Audi ', ' A4 ', ') ' Print (My_car.get_descri_name ()) My_car.yea R = 2016print (My_car.get_descri_name ()) #运行结果2017 A4 audi2016 A4 Audi

Modify by method

Class car (): "" "a simple attempt to simulate a car" "Def __init__ (self, make, model, year):" "The initialization of the car" "" Self.make = make        Self.model = model< C1/>self.year = year        self.odometer_reading = 100def get_descri_name (self): "" "Description Car" "" long_name = str (self.year) + " + Self.model + ' + self.makereturn long_namedef update (self, mile): "" "Update Mileage Value" "" If Mile > self.odometer_reading:            se lf.odometer_reading = Mileelse:print ("You can not roll back an odometer") def increment_odometer (self,mile): "" "Add Mileage" "" Self.odometer_reading + = Miledef read_odometer (self): "" "Print Car Mileage" "" Print ("This car has" + str (self.odometer_reading) + " Miles on it. ") My_car = car (' Audi ', ' A4 ', ') ' my_car.read_odometer () my_car.odometer_reading =    #直接修改里程值my_car. Update (200)     #通过方法修改里程my_car. Read_odometer () My_car.increment_odometer (Ten) My_car.read_odometer () #运行结果This car has miles On it. This car has a. miles on it. This car has a miles on it.

Inherited

If we want to inherit another class's properties, you can include the class name in parentheses after the class, for example:

class car (): "" "a simple attempt to simulate a car" "Def __init__ (self, make, model, year):" "" the initialization of the car " "Self.make = make Self.model = Model Self.year = Year self.odometer_reading = 100def Get_descri_name ( Self): "" "Description Car" "" long_name = str (self.year) + "+ Self.model +" + self.makereturn long_namedef update (self, mile): "" "" New mileage value "" "if mile > self.odometer_reading:self.odometer_reading = Mileelse:print (" You can ' t roll back an Odome Ter ") def increment_odometer (self,mile):" "" Increase Mileage "" "" self.odometer_reading + = Miledef read_odometer (self): "" "Print mileage of the car" " "Print (" This car had "+ str (self.odometer_reading) +" miles on it. ") Class Electriccar (CAR): "" "unique characteristics of electric vehicle" "" Def __init__ (self, make, model, year): "" Initializes the parent class's property "" "Super (). __init__ (Make, Model, year) My_tesla = Electriccar (' Tesla ', ' Model S ', ') ' Print (My_tesla.get_descri_name ()) #运行结果2016 Model S tesla< /pre>

To inherit the attributes of the parent class, you also need to add a special function super () to help Python associate the husband class with the subclass.

In Python2. In X, the format of Class Supper is as follows: Supper (eletric,self). __init__ (make, model, year)After you define properties and methods for subclasses to have one class inherit from another, you can add new properties and new methods to which the zone's molecular and parent classes belong. use an instance as an attribute
Class car (): "" "a simple attempt to simulate a car" "Def __init__ (self, make, model, year):" "The initialization of the car" "" self.make = make Self.model = Model  Self.year = Year self.odometer_reading = 100def get_descri_name (self): "" "Description Car" "" long_name = str (self.year) +            ' + Self.model + ' + self.makereturn long_namedef update (self, mile): "" "Update Mileage Value" "" If Mile > self.odometer_reading: self.odometer_reading = Mileelse:print ("You can not roll back an odometer") def increment_odometer (self,mile): "" "Increase Mileage "" "self.odometer_reading + = Miledef read_odometer (self):" "" Print Car Mileage "" "Print (" This car has "+ STR (self.odometer_ Reading) + "miles on it.") Class Battery (): "" "one-time simulated EV" "" Def __init__ (self,battery_size=70): "" Initialize Battery Properties "" "Self.battery_size = Battery_sizedef Describe_battery (self): "" Prints a message describing the battery capacity "" "Print (" This car has a "+ str (self.battery_size) +"-kwh battery. ") Class Electriccar (CAR): "" "unique characteristics of electric vehicle" "" Def __init__ (self, make, model, year): "" Initializes the parent class's property "" "Super (). __init__ (Make, Model, year) Self.battery =Battery () My_tesla = Electriccar (' Tesla ', ' Model S ', ') ' Print (My_tesla.get_descri_name ()) My_ Tesla.battery.describe_battery () #运行结果2016 Model S teslathis car has a 70-kwh battery.

Import class

importing single or multiple classesA file car.py
Class car (): "" "a simple attempt to simulate a car" "Def __init__ (self, make, model, year):" "The initialization of the car" "" self.make = make Self.model = Model  Self.year = Year self.odometer_reading = 100def get_descri_name (self): "" "Description Car" "" long_name = str (self.year) +            ' + Self.model + ' + self.makereturn long_namedef update (self, mile): "" "Update Mileage Value" "" If Mile > self.odometer_reading: self.odometer_reading = Mileelse:print ("You can not roll back an odometer") def increment_odometer (self,mile): "" "Increase Mileage "" "self.odometer_reading + = Miledef read_odometer (self):" "" Print Car Mileage "" "Print (" This car has "+ STR (self.odometer_ Reading) + "miles on it.") Class Battery (): "" "one-time simulated EV" "" Def __init__ (self,battery_size=70): "" Initialize Battery Properties "" "Self.battery_size = Battery_sizedef Describe_battery (self): "" Prints a message describing the battery capacity "" "Print (" This car has a "+ str (self.battery_size) +"-kwh battery. ") Class Electriccar (CAR): "" "unique characteristics of electric vehicle" "" Def __init__ (self, make, model, year): "" Initializes the parent class's property "" "Super (). __init__ (Make, Model, year) Self.battery =Battery () 

Create another file my_car.py, import a class

From  car Import carmy_car = car (' Audi ', ' A4 ', ' 2017 ')

Multiple classes can be stored in a module, so you can import more than one class at a time

From car Import Car,battery,electriccarmy_tesla = Electriccar (' Tesla ', ' Model S ', ' ") Print (My_tesla.get_descri_ Name ()) My_tesla.battery.describe_battery ()

Import the entire module

Import Car     #导入整个模块的时候, you need to use the period notation to access the required class My_tesla = car. Electriccar (' Tesla ', ' Model S ', ') ' Print (my_tesla.battery)

Import All Classes

From car import *    #导入所有的类

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.