object-oriented
Brief introduction
First, let's introduce the following object
Nowadays, there are two mainstream software development ideas:
One is process oriented, the other is object-oriented. Process oriented appeared earlier, typically represented by C language. It is very efficient to develop small and medium-sized projects, but it is difficult to apply to today's mainstream large and medium-sized project development scenarios. Object oriented appeared later, typically represented by languages such as Java or C + +, which is more suitable for large-scale development scenarios. The two development ideas have their own advantages and disadvantages.
For the process oriented idea: when a function needs to be implemented, the emphasis is on the development steps and processes. Each step needs to be done by yourself and you need to write your own code (do it yourself)
For the object-oriented idea: when a function needs to be implemented, the focus is not on the process and steps, but on who can help me do it (lazy, find someone to help me do it)
The three characteristics of object-oriented are encapsulation, inheritance and polymorphism.
Classes and objects
The original intention of object-oriented is to allow developers to define their own data types.
There are two core concepts: one is type (class for short) and the other is object (also known as instance).
Object is the core of object-oriented programming. In the process of using objects, in order to abstract a group of objects with common characteristics and behavior, another new concept class is proposed
In object-oriented language, "class" is used to simulate real things.
Take a simple example:
The design drawings of a mobile phone can be regarded as a class.
A specific, real mobile phone can be regarded as an object.
Summary: a class is abstract. When you use it, you usually find a specific existence of the class and use the specific existence. A class can find multiple objects.
- Class is a kind of thing, and object is the concrete implementation of this kind of thing.
- A class also has two parts: attribute and behavior. An object is a concrete instance of a class.
- Attribute: the feature description information of a thing, which is used to describe what a feature "is".
- Behavior: the ability action plan of things, which is used to explain "what things can do".
Defining classes and creating objects
Syntax:
class name:
Note: the class is named using the big hump nomenclature
1. Capitalize the first letter of each word
2. There is no underline between words
give an example:
Define a cat class
class Cat: def eat(self): print('%s I like fish' %(self.name)) def drink(self): print('The cat wants water') hellokitty = Cat() hellokitty.name = 'HK' print(hellokitty.name) print(hellokitty) hellokitty.eat() hellokitty.drink() # tom = Cat() # tom.eat() hellokitty Is an object, that is, in the code hellokitty.name and self.name It's the same """ self: Which object calls the method,self Is the reference of which object(Points to the memory address space of the object) When calling a method, the programmer does not need to pass self parameter(When defining, the first parameter must be self) """
Object property acquisition
Add and get the properties of the object
class Hero(object): """Defines a hero class that can move and attack""" def move(self): """Example method""" print("At the scene of the accident...") def attack(self): """Example method""" print("Issued a powerful ordinary attack...") # Instantiated a hero object, Tamil taidamier = Hero() # Add attributes and corresponding attribute values to the object taidamier.name = "Tamil" # full name taidamier.hp = 2600 # Life value taidamier.atk = 450 # aggressivity taidamier.armor = 200 # Armor # Pass Member selection operator to get the property value of the object print("hero %s Health value of :%d" % (taidamier.name, taidamier.hp)) print("hero %s Attack power :%d" % (taidamier.name, taidamier.atk)) print("hero %s Armor value of :%d" % (taidamier.name, taidamier.armor)) # Pass Member selection operator to get the instance method of the object taidamier.move() taidamier.attack() Heroic Tamil's HP :2600 The attack power of the hero Tamil :450 Armor value of hero Tamil :200 At the scene of the accident... Issued a powerful ordinary attack...
After the object is created and added with attributes, can these attributes be obtained in the instance method of the class? If so, what should be done?
Get the object properties through self within the method
class Hero(object): """Defines a hero class that can move and attack""" def move(self): """Example method""" print("At the scene of the accident...") def attack(self): """Example method""" print("Issued a powerful ordinary attack...") def info(self): """In the instance method of the class, through self Gets the properties of the object""" print("hero %s Health value of :%d" % (self.name, self.hp)) print("hero %s Attack power :%d" % (self.name, self.atk)) print("hero %s Armor value of :%d" % (self.name, self.armor)) # Instantiated a hero object, Tamil taidamier = Hero() # Add attributes and corresponding attribute values to the object taidamier.name = "Tamil" # full name taidamier.hp = 2600 # Life value taidamier.atk = 450 # aggressivity taidamier.armor = 200 # Armor # Pass Member selection operator to get the instance method of the object taidamier.info() # Just call the instance method info() to get the hero's properties taidamier.move() taidamier.attack() Heroic Tamil's HP :2600 The attack power of the hero Tamil :450 Armor value of hero Tamil :200 At the scene of the accident... Issued a powerful ordinary attack...
Magic method
__ init__ Function, which can modify the value of the attribute when instantiating the object.
class Hero(object): """Defines a hero class that can move and attack""" # The methods provided in Python classes that start with two underscores and end with two underscores are magic methods__ init__ () is a magic method, which is usually used for attribute initialization or assignment. # If the class surface is not written__ init__ Method, Python will automatically create it, but will not perform any operation, # If you want to complete the functions you want, you can define them yourself__ init__ method, # So whether you write it or not in a class__ init__ There must be a way__ init__ method. def __init__(self): """ Method is used for variable initialization or assignment. It will be called automatically when the class instantiates the object""" self.name = "Tamil" # full name self.hp = 2600 # Life value self.atk = 450 # aggressivity self.armor = 200 # Armor def info(self): """In the instance method of the class, through self Gets the properties of the object""" print("hero %s Health value of :%d" % (self.name, self.hp)) print("hero %s Attack power :%d" % (self.name, self.atk)) print("hero %s Armor value of :%d" % (self.name, self.armor)) def move(self): """Example method""" print("At the scene of the accident...") def attack(self): """Example method""" print("Issued a powerful ordinary attack...") # Instantiates a hero object and automatically calls__ init__ () method taidamier = Hero() # Pass Member selection operator to get the instance method of the object taidamier.info() # Just call the instance method info() to get the hero's properties taidamier.move() taidamier.attack()
Parametric__ init__ () method
class Hero(object): """Defines a hero class that can move and attack""" def __init__(self, name, skill, hp, atk, armor): """ __init__() Method to initialize or assign variables""" # Hero name self.name = name # skill self.skill = skill # HP: self.hp = hp # aggressivity self.atk = atk # Armor self.armor = armor def move(self): """Example method""" print("%s At the scene of the accident..." % self.name) def attack(self): """Example method""" print("Made a powerful move%s..." % self.skill) def info(self): print("hero %s Health value of :%d" % (self.name, self.hp)) print("hero %s Attack power :%d" % (self.name, self.atk)) print("hero %s Armor value of :%d" % (self.name, self.armor)) # When you instantiate a hero object, parameters are passed to the object's__ init__ () method taidamier = Hero("Tamil", "Whirlwind ", 2600, 450, 200) gailun = Hero("Galen", "Big sword", 4200, 260, 400) # The direct output object is the address print(gailun) # <__main__.Hero object at 0x0318B100> print(taidamier) # <__main__.Hero object at 0x0318B0D0> # Separate saving of attribute values of different objects print(id(taidamier.name)) print(id(gailun.name)) # Different objects of the same class are shared by instance methods print(id(taidamier.move())) # Tamil is in the former incident site # 2045877480 print(id(gailun.move())) # Galen is at the former scene # 2045877480
Output results:
<__main__.Hero object at 0x0318B100> <__main__.Hero object at 0x0318B0D0> 51928864 51928912 Tamil is at the site of the incident... 2045877480 Galen is at the scene of the accident... 2045877480
If it is an attribute, its address value is directly output. If it is a method, execute the method first to output the address value
Through a class, you can create multiple objects, just as you can create multiple entities through a stencil
In init(self), there is one parameter named self by default. If two arguments are passed when creating an object, then__ init__ In (self), self is listed as the first formal parameter, and two formal parameters are required, such as__ init__(self,x,y)
be careful:
① Get the attributes and instance methods inside the class, and get them through self;
② Get the properties and instance methods outside the class, and get them through the object name.
③ If a class has multiple objects, the properties of each object are saved separately and have their own independent addresses;
④ However, the instance method is shared by all objects and occupies only one memory space. Class will use self to determine which object called the instance method.
__ str__ function
__ str__ Function, which requires to return a string. The information of this string should be able to organize the information of the object. When we use the print function to print the object, it is actually printed__ str__ The string returned by the function.
class Hero(object): """Defines a hero class that can move and attack""" def __init__(self, name, skill, hp, atk, armor): """ __init__() Method to initialize or assign variables""" # Hero name self.name = name # Instance variable # skill self.skill = skill # HP: self.hp = hp # Instance variable # aggressivity self.atk = atk # Armor self.armor = armor def move(self): """Example method""" print("%s At the scene of the accident..." % self.name) def attack(self): """Example method""" print("Made a powerful move%s..." % self.skill) # def info(self): # print("health value of hero% s:% d"% (self.name, self. HP)) # print("attack power of hero% s:% d"% (self.name, self. ATK)) # print("armor value of hero% s:% d"% (self. Name, self. Armor)) def __str__(self): """ This method is a magic method (Magic Method) ,Used to display information This method requires return One data, and only self A parameter when outside the class print(object) Then print this data """ return "hero <%s> Data: Health %d, aggressivity %d, Armor %d" % (self.name, self.hp, self.atk, self.armor) taidamier = Hero("Tamil", "Whirlwind ", 2600, 450, 200) gailun = Hero("Galen", "Big sword", 4200, 260, 400) # If not__ str__ The default address of the print object in memory. # When an instantiated object of a class has__ str__ Method, the printed object is printed__ str__ Return value of. print(taidamier) print(gailun) # View the documentation of the class, that is, the comments of the class print(Hero.__doc__)
encapsulation
Public members can be used publicly, that is, they can be accessed inside a class or used in an external program. In Python, class member functions and member variables are public by default.
Private members cannot be accessed directly outside the class. They are generally accessed and operated inside the class, or accessed outside the class by calling the public member method of the object, which is an important embodiment of the encapsulation characteristics of the class.
__ XXX: it starts with two underscores and indicates the private member of the class. Generally, only the class object can access it, and the subclass object cannot directly access the member, but it can be accessed through a special way such as "object name. Class name _xxx".
class Point: x = 10 __y = 20 z = 30 def get_x(self): returnself.x def get_y(self): returnself.__y def __get_z(self): returnself.z
inherit
Single inheritance
One of the main benefits of object-oriented programming is code reuse. One of the ways to realize this reuse is through inheritance mechanism. Inheritance is used to specify that a class will obtain most or all of its functions from its parent class. It is a feature of object-oriented programming. This is a very powerful function, which is convenient for users to make several or more modifications to existing classes to create a new class. A new class is called a subclass or derived class, and the main class that inherits properties from it is called a base class or a parent class.
Simply put, for example:
Subclass B inherits from parent class A and also obtains the methods in the parent class, so the object B created by subclass B can use the methods in a
class A(object): def eat(self): print("I want instant noodles ") class B(A): pass b=B() b.eat()
multiple inheritance
Python subclasses can inherit one base class or multiple base classes, which is called multiple inheritance.
Let's take a simple example
Subclass B inherits parent class A and subclass C inherits parent class B. in such multiple inheritance, the last subclass object will find the method of its parent along the path of parent inheritance
class A(object): def eat(self): print("I want instant noodles ") class B(A): pass class C(B): pass c=C() c.eat()
Note: it is not recommended to use multiple inheritance, because if the methods in parent class A and parent class B are the same, there will be problems of overwriting or loading order.
polymorphic
Polymorphism means that the same method of the base class has different realizations and behaviors in different derived class objects. Different derived class objects call the same base class method and produce different execution results, which can increase the flexibility of external calling of the code. Polymorphism is based on inheriting and rewriting the parent class method. Polymorphism is only a skill of calling methods and will not affect the internal design of the class.
Understanding and expression: for example, dog and Xiaotian dog introduce themselves at the same time. Xiaotian dog has his own introduction. Dog has his own introduction
class Amile(): def print_self(self): pass class Dog(Amile): def print_self(self): print("I'm rhubarb ") class xiaotq(Amile): def print_self(self): print("I'm a howling dog ") def jieshao(temp): temp.print_self() dog=Dog() jieshao(dog) dog2=xiaotq() jieshao(dog2)