Python advanced (4): First understanding of object-oriented, python advanced

Source: Internet
Author: User

Python advanced (4): First understanding of object-oriented, python advanced

Everything is an object!

Preview:

# Write a circle class Square: def _ init _ (self, length_of_side): self. length_of_side = length_of_side def square (self): 'area 'Return self. length_of_side * self. length_of_side def perimeter (self): 'Perimeter 'return self. length_of_side * 4 Square = Square (2) print (Square. square () print (square. perimeter ())
Pre-Exercise

 

1. Process-> object-oriented

Process-oriented: Code stacking from top to bottom based on business logic

Function: encapsulate a function code into a function. You do not need to write it again later. You only need to call the function.

Object-oriented: classifies and encapsulates functions to make development faster, better, and stronger ..."

 

Ii. Initial class and Object

In python, everything is an object, and the type is essentially a class, so you have used the class for a long time.

In python, features are represented by variables and functions. Therefore, a type of things with the same features and skills are 'class', and objects are specific things of this type.

1. Class

# Define a human class keyword and define the function's def similarly class Person: role = 'body' # role variable attribute -- Static attribute def walk (self ): # self must be written (which will be introduced later), also called dynamic attribute print ("person is walking..."
Class

Attribute reference (class name. Attribute)

Class Person: role = 'body' def walk (self): print ("person is walking... ") print (Person. role) # view the role attribute print (Person. walk) # reference a person's walking method. Note that this is not called
Reference

Instantiation: the class name is instantiated. It will automatically trigger the operation of the _ init _ function. You can use it to customize your own features for each instance.

Syntax: Object Name = Class Name (parameter)

Class Person: # define a human role = 'person 'def _ init _ (self, name): self. name = name # each role has its own nickname. cangjing = Person ('hangjing ') xiaozeze = Person ('heze ') # The instantiation process is the process of class> Object
Instantiation

The class name () is equivalent to executing Person. _ init _ (). After executing _ init _ (), an object is returned. This object is similar to a dictionary and contains some attributes and methods of this person.

View attributes and call Methods

Print (cangjing. name) # view object attributes direct object name. attribute name

Self: when instantiating, the object/instance itself is automatically passed to the _ init _ parameter. aliases are not recommended when aliases are allowed.

Class supplement

I. Where are the attributes of the defined class stored? There are two ways to view dir (Class Name): Find a name list class name. _ dict __: identifies a dictionary. key indicates the attribute name, and value indicates the attribute value. 2. Special Class Attribute Class Name. _ name __# Class name (string) class name. _ doc __# document string class name of the class. _ base __# name of the first parent class of the class (which will be discussed during inheritance. _ bases __# name of the class, which consists of all the tuples of the class parent class. _ dict __# name of the class's dictionary attribute class. _ module __# name of the module class where the class definition is located. _ class __# class corresponding to the instance (only in the new class)
Class Attribute supplement

2. Object

Let's write about a human dog war: Now we need to make a little change to our class. In addition to being able to walk, humans should have some attack skills.

Class Person: # define a human role = 'person '# The role attributes of a person are def _ init _ (self, name, aggressivity, life_value): self. name = name # each role has its own nickname; self. aggressivity = aggressivity # each role has its own attack power. self. life_value = life_value # each role has its own life value; def attack (self, dog): # A person can attack a dog. The dog here is also an object. Dog. life_value-= self. aggressistmprint ("{0} Hit {1}, {1} remaining blood volume {2 }". format (self. name, dog. name, dog. life_value ))
Human

An object is an actual example of a class, that is, an instance. An object/instance has only one function: attribute reference

Cangjing = Person ('hangjing ',) print (cangjing. name) print (cangjing. aggressi.pdf) print (cangjing. life_value)

You can also reference a method because the method is also an attribute (dynamic attribute ).

Class name: class property = None def _ init _ (self, parameter 1, parameter 2): self. object Property 1 = parameter 1 self. object Property 2 = parameter 2 def method name (self): pass def method name 2 (self): pass object name = Class Name (1, 2) # object is an instance, represents a specific thing # Class Name (): class name + brackets is to instantiate a class, which is equivalent to calling the _ init _ method # Passing parameters in brackets, you do not need to pass self to the parameter. The other parameters correspond to each other in init # An object name is returned in the result. object attribute 1 # view object attributes and use the object name directly. the property name can be the object name. method Name () # Call the method in the class and directly use the object name. method Name () # Add an attribute object to the object. new attribute name = 1000
Summary

Interaction between objects

Now that we want to be a dog, we already have someone. Now we want to create another dog class, and the dog will bite us. We will give the dog a bite method. With the dog class, let's instantiate another real dog. People and dogs can fight.

Class Dog: # define a dog class role = 'Dog' # Dog's role attributes are dog def _ init _ (self, name, breed, aggressivity, life_value): self. name = name # each dog has its own nickname. self. breed = breed # each dog has its own breed. self. aggressivity = aggressivity # each dog has its own attack power. self. life_value = life_value # each dog has its own life value; def bite (self, people): # dogs can bite people. Here the dog is also an object. People. life_value-= self. aggressistmprint ("{0} bit {1}, {1} remaining blood volume {2 }". format (self. name, people. name, people. life_value ))
Dog

Instantiate a wolf dog:

Egon = Dog ('egon', 'Wolf dog', 100,20000) # creates a real Dog egon

Interactive cangjing hitting egon/egon biting cangjing

A = Person ("cangjing",) B = Dog ("egon", "Langu",) a. attack (B) B. bite ()
Interaction

Complete Human and dog war code:

Class Person: # define a human role = 'person '# The role attributes of a person are def _ init _ (self, name, aggressivity, life_value): self. name = name # each role has its own nickname; self. aggressivity = aggressivity # each role has its own attack power. self. life_value = life_value # each role has its own life value; def attack (self, dog): # A person can attack a dog. The dog here is also an object. Dog. life_value-= self. aggressistmprint ("{0} Hit {1}, {1} remaining blood volume {2 }". format (self. name, dog. name, dog. life_value) class Dog: # define a dog class role = 'Dog' # the Dog's role attributes are dog def _ init _ (self, name, breed, aggressivity, life_value): self. name = name # each dog has its own nickname. self. breed = breed # each dog has its own breed. self. aggressivity = aggressivity # each dog has its own attack power. self. life_value = life_value # each dog has its own life value; def bite (self, people): # Dog You can bite people. The dog here is also an object. People. life_value-= self. aggressistmprint ("{0} bit {1}, {1} remaining blood volume {2 }". format (self. name, people. name, people. life_value) a = Person ("cangjing",) B = Dog ("egon", "Langu",) while True:. attack (B) B. bite (a) if. life_value <= 0: print (. name + "quilt" + B. name + "biting! ") Break if B. life_value <= 0: print (B. name +" killed by "+ a. name +! ") Break
Egon vs. cangjing

 

Iii. Class namespaces and objects and instance namespaces

When a class is created, a namespace of the class is created to store all the names defined in the class. These names are called class attributes.

Static attributes are variables defined directly in the class, and dynamic attributes are the methods defined in the class.

The data attributes of the class are shared to all objects.

Print (id (a. role) print (id (Person. role) # Same

The dynamic attributes of a class are bound to all objects.

Print (a. attack) print (Person. attack) # different

When you create an object/instance, an object/instance namespace is created to store the object/Instance name, which is called the object/instance attribute. name will first find the name from the namespace of obj. If it cannot be found, it will be found in the class. If it cannot be found, it will find the parent class... an exception is thrown if none of them are found.

 

Iv. object-oriented combination

A combination refers to a combination of classes that use the object of another class as the data attribute.

Class Weapon: ''' this is the data type of a Weapon in the game ''' def _ init _ (self, name, price, aggrev, life_value): self. name = name # weapon name self. price = price # weapon price self. aggrev = aggrev # weapon damage bonus self. life_value = life_value # weapon volume addition def update (self, obj): # obj is the person carrying this equipment. money-= self. price # The people who use this weapon spend money to buy so the corresponding money should be reduced by obj. aggressivity + = self. aggrev # carrying this equipment can increase the number of attacks. obj. life_value + = self. life_value # with this equipment, you can increase the life value def prick (self, obj): # This is the active skill of the equipment. life_value-= 3000 # assume the attack power is 3000
Weapons

Complete code for combined interaction between human and dogs:

Class Person: # define a human '''. This is the data type of a person in a game. ''' role = 'body' # The role attribute of a person is def _ init _ (self, name, aggressivity, life_value): self. name = name # each role has its own nickname; self. aggressivity = aggressivity # each role has its own attack power. self. life_value = life_value # each role has its own life value; def attack (self, dog): # A person can attack a dog. The dog here is also an object. Dog. life_value-= self. aggressistmprint ("{0} Hit {1}, {1} remaining blood volume {2 }". format (self. name, dog. name, dog. life_value) class Dog: # define a dog class ''' this is the data type of a dog in a game ''' role = 'Dog' # the dog's role attributes are dog def _ init _ (self, name, breed, aggressivity, life_value): self. name = name # each dog has its own nickname. self. breed = breed # each dog has its own breed. self. aggressivity = aggressivity # each dog has its own attack power. self. life_value = life_value # each dog has its own life value; def Bite (self, people): # A dog can bite. A dog here is also an object. People. life_value-= self. aggressistmprint ("{0} bit {1}, {1} remaining blood volume {2 }". format (self. name, people. name, people. life_value) class Weapon: ''' this is the data type of a Weapon in the game. ''' def _ init _ (self, name, price, aggrev, life_value): self. name = name # weapon name self. price = price # weapon price self. aggrev = aggrev # weapon damage bonus self. life_value = life_value # weapon volume addition def update (self, obj): # obj is the person carrying this equipment. money-= self. price # people who use this weapon spend money to buy the corresponding money Reduce obj. aggressivity + = self. aggrev # carrying this equipment can increase the number of attacks. obj. life_value + = self. life_value # with this equipment, you can increase the life value def prick (self, obj): # This is the active skill of the equipment. life_value-= 3000 # assume that the attack power is 3000 print ("{0} launch initiative: Yunlong ==>{ 1} remaining blood volume {2 }". format (self. name, obj. name, obj. life_value) a = Person ("cangjing",) B = Dog ("egon", "Langu",) c = Weapon ("Yunlong whip", 40, 2000). money = 2000 # determine whether to buy a weapon if. money> c. price: c. update () A. weapon = c # Start of the war while True:. attack (B) if B. life_value <= 0: print (B. name + "quilt" +. name + "killed! ") Break a. weapon. prick (B) if B. life_value <= 0: print (B. name +" Hacked "+ a. name +! ") Break B. bite (a) if a. life_value <= 0: print (a. name +" killed by "+ B. name +! ") Break
Upgraded egon vs. cangjing

 

Mind Map:

 

Preview answer:

# Circular class Circle: def _ init _ (self, radius): self. radius = radius def area (self): 'area 'return self. radius ** 2*3.14 def perimeter (self): 'Perimeter 'return self. radius * 2*3.14 Circle = Circle (8) print (Circle. area () print (circle. perimeter ())
Preview answer

 

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.