9 classes and objects
9.1 object oriented
Class and object are important concepts in object-oriented. Object oriented is a kind of programming idea, that is, to build a software system according to the thinking mode of the real world.
9.2 definition class
All data types in Python are classes. We can customize classes, that is, create a new data type. The syntax format is as follows:
class Car(object): # Class body pass
Car class inherits object class, which is the root class of all classes. In Python, any class directly or indirectly inherits object ', and some codes can be omitted when directly inheriting object.
Note: the pass statement is only used to maintain the integrity of the program structure. When programming, if we don't want to write some code immediately and don't want syntax errors, we can use pass statement to occupy bits.
9.3 creating objects
Classes are a bit like biological concepts. We can also call objects in a class instances.
# coding = utf-8 class Car(object): # Class body pass car = Car()
Unlike C + +, Python does not require programmers to manually release objects.
9.4 members of class
Member variables, also known as data members, hold the data of a class or object. For example, the student's name and student number.
Constructor is a special function used to initialize the member variables of a class.
Member methods are functions defined in a class.
Property is a special method provided to encapsulate a class.
Instance variables and instance methods belong to objects and are called through objects, while class variables and class methods belong to classes and are called through classes.
9.4.1 instance variables
Instance variables are the "data" unique to the individual object, such as the dog's name and age.
# coding = utf-8 class Dog: def __init__(self, name, age): self.name = name # Create and initialize instance variable name self.age = age # Create and initialize instance variables d = Dog('Ball ball', 2) print('Our dog's name is{0},{1}Years old.'.format(d.name, d.age))
Self in the class represents the current object. The self parameter in the construction method indicates that the method belongs to an instance, self Self in age means that age belongs to an instance, that is, an instance member variable.
9.4.2 construction method
Class__ init__ () method is a very special method used to create and initialize instance variables. This method is "construction method". When defining _init_ () method, its first parameter should be self, and the subsequent parameters are used to initialize instance variables. When calling the construction method, it is not necessary to pass in the self parameter.
The example code of the construction method is as follows:
# coding = utf-8 class Dog: def __init__(self, name, age, sex='female'): self.name = name self.age = age self.sex = sex d1 = Dog('Ball ball', 2) d2 = Dog('ha-ha',1,'female') d3 = Dog(name = 'Mop', sex='female',age=3) print('{0}:{1}year{2}. '.format(d1.name, d1.age, d1.sex)) print('{0}:{1}year{2}. '.format(d2.name, d2.age, d2.sex)) print('{0}:{1}year{2}. '.format(d1.name, d3.age, d3.sex))
9.4.3 example method
Like instance variables, instance methods are unique to an instance (or object) individual.
When defining an instance method, its first parameter should also be self, which will bind the current instance to the method, which also shows that the method belongs to an instance. When calling a method, you do not need to pass in self, which is similar to constructing a method.
Let's take a look at an example of defining an instance method:
# coding = utf-8 class Dog: # Construction method def __init__(self, name, age, sex='female'): self.name = name self.age = age self.sex = sex # Example method def run(self): print("{}Running...".format(self.name)) # Example method def speak(self, sound): print('{}I'm yelling,"{}"!'.format(self.name, sound)) dog = Dog('Ball ball', 2) dog.run() dog.speak('Woof, woof')
Class 9.4.4 variables
Class variables are variables belonging to a class and do not belong to a single object.
For example, there is an Account class, which has three member variables: amount and interest_rate and owner. Amount and owner are different for each Account, while interest_ The rate is the same for all accounts. Amount and owner are instance variables, and interest rate is a variable shared by all Account instances. It belongs to class and is called "class variable".
The example code of class variable is as follows:
# coding = utf-8 class Account: interest_rate = 0.0568 def __init__(self, owner, amount): self.owner = owner self.amount = amount account = Account('Tony', 800000.0) print('Account Name:{0}'.format(account. owner)) print('Account amount:{0}'.format(account.amount)) print('Interest rate:{0}'.format(Account.interest_rate))
Class 9.4.5 methods
Class methods are similar to class variables. They belong to classes, not individual instances. When defining a class method, its first parameter is not self, but the class itself.
The example code for defining class methods is as follows:
# coding = utf-8 class Account: interest_rate = 0.0668 def __init__(self, owner, amount): self.owner = owner self.amount = amount # Class method @classmethod def interest_by(cls, amt): # cls represents itself return cls.interest_rate * amt # cls can be replaced by Account interest = Account.interest_by(12000.0) print('Calculation of interest:{0:.4f}'.format(interest))
9.5 encapsulation
Encapsulation is one of the important basic characteristics of object-oriented. Encapsulation hides the internal details of the object and only retains a limited external interface. External callers do not care about the internal details of the object, making it easy to operate the object.
9.5.1 private variables
In order to prevent external callers from accessing the internal data (member variables) of the class at will, the internal data (member variables) will be encapsulated as "private variables". External callers can only call private variables through methods.
By default, variables in Python are public and can be accessed outside the class. If you want them to be private variables, just double underline the variables.
# coding = utf-8 class Account: __interest_rate = 0.0568 def __init__(self, owner, amount): self.owner = owner self.__amount = amount def desc(self): print("{0} amount of money:{1} Interest rate:{2}. ".format(self.owner, self.__amount, Account.__interest_rate)) account = Account('Tony', 800000.0) account.desc() print('Account Name:{0}'.format(account. owner)) print('Account amount:{0}'.format(account.__amount)) # Error occurred print('Interest rate:{0}'.format(Account.__interest_rate)) # Error occurred
9.5.2 private method
The encapsulation of private methods is similar to that of private variables. Adding a double underscore before the method is a private method. The example code is as follows:
# coding = utf-8 class Account: __interest_rate = 0.0568 def __init__(self, owner, amount): self.owner = owner self.__amount = amount def __get_info(self): return "{0} amount of money:{1} Interest rate:{2}. ". format(self.owner, self.__amount,Account.__interest_rate) def desc(self): print(self.__get_info()) account = Account('Tony', 800000.0) account.desc() account.__get_info() # An error occurred
9.5.3 use attributes
In order to realize the encapsulation of objects, there should be no public member variables in a class. These member variables should be designed as private and then accessed through public set (assignment) and get (value) methods.
The set and get methods are used for encapsulation. The example code is as follows:
# coding = utf-8 class Dog: # Construction method def __init__(self, name, age, sex='female'): self.name = name self.__age = age self.sex = sex # Example method def run(self): print("{}Running...".format(self.name)) # get method def get_age(self): return self.__age # set method def set_age(self, age) self.__age = age dog = Dog('Ball ball', 2) print('Dog age: {}'.format(dog.get_age)) dog.set_age(3) print('Modified dog age:{}'.format(dog.get_age())
Modify the above example by using the attribute method. The code is as follows:
# coding = utf-8 class Dog: # Construction method def __init__(self, name, age, sex='female'): self.name = name self.__age = age self.sex = sex # Example method def run(self): print("{}Running...".format(self.name)) @property def age(self): # Replace get_age(self) return self.__age @age.setter def age(self, age): # Substitute set_age(self,age) self.__age = age dog = Dog('Ball ball', 2) print('Dog age: {}'.format(dog.age)) dog.age = 3 # dog.set_age(3) print('Modified dog age:{}'.format(dog.age)
9.6 inheritance
Inheritance is also one of the important basic characteristics of object-oriented.
9.6.1 inheritance in Python
In Python, make it clear that a subclass inherits from the parent class. When defining a class, use a pair of parentheses after the class to specify its parent class.
# -*- coding: utf-8 -*- class Animal: def __init__(self, name): self.name = name # Instance variable name def show_info(self): return "Animal name:{0}".format(self.name) def move(self): print("Move...") class Cat(Animal): def __init__(self, name, age): super().__init__(name) # Call the parent class constructor to initialize the parent class member variable self.age = age # Instance variable age cat = Cat('Tom', 2) cat.move() print(cat.show_info())
When a subclass inherits the parent class, it will inherit the public member variables and methods of the parent class.
9.6.2 multiple inheritance
Python supports multiple inheritance. If there are the same member methods or member variables in multiple parent classes, the child class will inherit the member methods or member variables in the left parent class first, and the inheritance level from left to right is from high to low.
The example code is as follows:
# -*- coding: utf-8 -*- class Horse: def __init__(self, name): self.name = name # Instance variable name def show_info(self): return "Horse's name:{0}".format(self.name) def run(self): print("Horse running...") class Donkey: def __init__(self, name): self.name = name # Instance variable name def show_info(self): return "Donkey's name:{0}".format(self.name) def run(self): print("The donkey runs...") def roll(self): print("glutinous rice rolls stuffed with red bean paste") class Mule(Horse, Donkey): def __init__(self, name, age): super().__init__(name) self.age = age # Instance variable age m = Mule('mule',1) m.run() # Inherit the parent class Horse method m.roll() # Inherit the parent class Donkey method print(m.show_info()) # Inherit the parent class Horse method
9.6.3 method rewriting
If the method name of the subclass is the same as that of the parent class, in this case, the method of the subclass overrides the method of the parent class with the same name. The example code is as follows:
# -*- coding: utf-8 -*- class Horse: def __init__(self, name): self.name = name # Instance variable name def show_info(self): return "Horse's name:{0}".format(self.name) def run(self): print("Horse running...") class Donkey: def __init__(self, name): self.name = name # Instance variable name def show_info(self): return "Donkey's name:{0}".format(self.name) def run(self): print("The donkey runs...") def roll(self): print("glutinous rice rolls stuffed with red bean paste") class Mule(Horse, Donkey): def __init__(self, name, age): super().__init__(name) self.age = age # Instance variable age def show_info(self): return "Mule:{0},{1}Years old.".format(self.name, self.age) m = Mule('mule',1) m.run() # Inherit the parent class Horse method m.roll() # Inherit the parent class Donkey method print(m.show_info()) # Inherit the parent class Horse method
9.7 polymorphism
Polymorphism is also one of the important basic characteristics of object-oriented. "Polymorphism" means that objects can show a variety of forms.
9.7.1 inheritance and polymorphism
After multiple subclasses inherit the parent class and override the parent method, the objects created by these subclasses are polymorphic. And these objects implement parent methods in different ways. The example code is as follows:
# -*- coding: utf-8 -*- class Animal: def speak(self): print('Animals bark, but I don't know what's barking') class Dog(Animal): def speak(self): print("Woof, woof") class Cat(Animal): def speak(self): print("cat ") an1 = Dog() an2 = Cat() an1.speak() an2.speak()
There is another way:
# -*- coding: utf-8 -*- class Animal: def speak(self): print('Animals bark, but I don't know what's barking') class Dog(Animal): def speak(self): print("Woof, woof") class Cat(Animal): def speak(self): print("cat ") class Car: def speak(self): print("Small train: woo woo") def start(obj): obj.speak() start(Dog()) start(Cat())