In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article is about the object-oriented features of Python. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Introduction to three major features of object-oriented
Encapsulation (hiding): hide the properties and implementation details of the object, and provide the necessary methods to the outside world.
Inheritance: let the subclass have the characteristics of the parent class, improving the reusability of the code. The design is a kind of incremental evolution. When the original parent class design remains unchanged, new functions can be added or existing algorithms can be improved.
Polymorphism: a method call produces different behavior depending on the object.
Inherit
Inheritance is a very important means of code reuse. The existing class is called "parent class or base class", and the new class is called "subclass or derived class".
Grammatical format
Python supports multiple inheritance, and a subclass can inherit multiple parent classes. The syntax format of inheritance is as follows:
Class subclass name (parent class 1 [, parent class 2, …]) :
type body
If no parent class is specified in the class definition, the default parent class is the object class. That is, object is the parent of all classes, and some default implementations common to all classes are defined, such as: new ().
When you define a subclass, you must call the constructor of the parent class in its constructor. The call format is as follows:
Parent class name .init (self, parameter list)
# basic use of test inheritance class Person (): def _ init__ (self, name, age): self.name = name self.__age = age # Private attribute def print_name (self): print (self.name) class Student (Person): def _ init__ (self, name, age, id): Person.__init__ (self, name) Age) self.id = idstu = Student ('sherry',24,'2017') stu.print_name () print (Student.mro ()) # View the inheritance hierarchy of the class print (dir (stu)) # print all methods and properties print (stu._Person__age) # access output of private properties inherited from the parent class: sherry [,] [' _ Person__age','_ class__','_ _ delattr__' '_ _ dict__',' _ _ dir__','_ _ doc__','_ _ eq__','_ _ format__','_ _ ge__','_ _ getattribute__','_ _ gt__','_ _ hash__','_ _ init__','_ init_subclass__','_ le__','_ lt__','_ _ module__' '_ _ ne__',' _ _ new__','_ _ reduce__','_ _ reduce_ex__','_ _ repr__','_ _ setattr__','_ _ sizeof__','_ _ str__','_ subclasshook__','_ _ weakref__', 'id',' name', 'print_name'] 24
1. Class member inheritance and override member inheritance: subclasses inherit all members of the parent class except constructors, including methods, properties, private methods, private properties, but private methods and properties cannot be accessed directly.
two。 Method rewriting: subclasses can redefine methods in the parent class, which overrides the methods of the parent class, also known as "override"
# Test class Person (): def _ init__ (self, name, age): self.name = name self.__age = age # private attribute def print_name (self): print (self.name) class Student (Person): def _ init__ (self, name, age, id): Person.__init__ (self, name) Age) self.id = id def print_name (self):''overrides the method of the parent class' 'print (' my name is', self.name) stu = Student ('sherry',24,'2017') stu.print_name () output: my name is sherry to view the inheritance hierarchy of the class
You can output the inheritance hierarchy of the class through the class method mro () or the class property _ _ mro__.
Class Person (): def _ init__ (self, name, age): self.name = name self.__age = age # Private attribute def print_name (self): print (self.name) class Student (Person): def _ init__ (self, name, age, id): Person.__init__ (self, name) Age) self.id = id def print_name (self):''overrides the method of the parent class' 'print (' my name is', self.name) # stu = Student ('sherry',24,'2017') print (Student.mro ()) output: [,] object root class
The object class is the parent of all classes, so all classes have properties and methods of the object class.
Dir () View object properties # basic test inheritance uses class Person (): def _ init__ (self, name, age): self.name = name self.__age = age # Private attributes def print_name (self): print (self.name) class Student (Person): def _ init__ (self, name, age, id): Person.__init__ (self, name) Age) self.id = id def print_name (self):''print (' my name is', self.name) obj = object () stu = Student ('sherry',24,'2017') print (dir (obj)) print (dir (stu)) output: [_ _ class__',' _ delattr__','_ _ dir__','_ doc__' '_ _ eq__',' _ _ format__','_ _ ge__','_ _ getattribute__','_ _ gt__','_ _ hash__','_ _ init__','_ _ init_subclass__','_ _ le__','_ _ lt__','_ ne__','_ new__','_ reduce__','_ _ reduce_ex__' '_ _ repr__',' _ _ setattr__','_ _ sizeof__','_ _ str__','_ _ subclasshook__'] ['_ Person__age','_ _ class__','_ _ delattr__','_ _ dict__','_ _ dir__','_ _ dir__','_ doc__','_ eq__','_ format__','_ _ ge__' '_ _ getattribute__',' _ _ gt__','_ _ hash__','_ _ init__','_ _ init_subclass__','_ _ le__','_ _ lt__','_ _ module__','_ _ ne__','_ _ new__','_ reduce__','_ reduce_ex__','_ repr__','_ _ setattr__' Rewriting of'_ _ sizeof__','_ _ str__','_ _ subclasshook__','_ _ weakref__', 'id',' name', 'print_name'] str () method
Object has a _ _ str__ () method that returns a description of the object, corresponding to the built-in function str (). It is often used in the print () method to help us view the information about the object. Str () can be overridden.
Class Person (): def _ init__ (self, name, age): self.name = name self.__age = age # Private attribute def print_name (self): print (self.name) def _ _ str__ (self): return 'name: {0} age: {1}' .format (self.name, self.__age) p = Person ('sherry') 24) print (p) output: name:sherry age:24 multiple inheritance
Python supports multiple inheritance, and a subclass can have multiple "direct parent classes". In this way, it has the characteristics of "multiple parent classes". However, because this will be extremely complicated by the "overall level of the class", try to avoid using it. (java does not support multiple inheritance)
Class A (): passclass B (): passclass C (C.mro B): passprint (C.mro ()) output: [,] MRO ()
Python supports multiple inheritance, and if there is a method with the same name in the parent class, the interpreter will search sequentially "from left to right" if the child class does not specify a parent class name.
Class A (): passclass B (): passclass C (C.mro B): passprint (C.mro ()) output: [,] super () to get the parent class definition
In the subclass, if you want to get the method of the parent class, we can do it through super (). Super () gets the definition of the parent class (not the object of the parent class).
# Test super () class A (): def say (self): print ('aa') class B (A): def say (self): super (). Say () # call parent method A.say (self) # call parent method print (' bb') b = B () b.say () output: aaaabb polymorphism
Polymorphism means that the same method call may produce different behaviors due to different objects.
Note the following two points about polymorphism:
1. Polymorphism is the polymorphism of methods, and there is no polymorphism in attributes.
two。 There are two necessary conditions for the existence of polymorphism: inheritance and method rewriting.
# Polymorphic class Man (): def eat (self): print ('eatural') class Chinese (Man): def eat (self): print ('eat with chopsticks') class English (Man): def eat (self): print (' eat with fork') class Indian (Man): def eat (self): print ('eat with hand') def manEat (m): if isinstance (m) Man): m.eat () else: print ('can not eatable') ManEat (Man ()) manEat (Chinese ()) manEat (English ()) manEat (Indian ()) output: eat with chopstickseat with forkeat with hand special methods and overload operators
The python heavy operator is actually implemented by calling a special method of the object.
A = 20b = 30print (aqb) print (a. Output: 5050)
Common special methods:
Each operator actually corresponds to the corresponding method:
# Test operator overload class Person (): def _ init__ (self, name): self.name = name def _ add__ (self, other): if isinstance (other, Person): return'{0}-{1} '.format (self.name, other.name) def _ _ mul__ (self, other): if isinstance (other Int): return self.name * otherp1 = Person ('Sherry') p2 = Person (' Lily') print (p1 + p2) print (p1x10) output: Sherry-LilySherrySherrySherrySherrySherrySherrySherrySherrySherrySherry special attributes
Python contains a lot of double underscore start and end attributes. These are special properties and have special uses. Common special attributes are listed here:
# Test special attributes class A (): def say (self): print ('aa') class B (): def say (self): print (' bb') class C (BMague A): def _ _ init__ (self) Name): super (). _ init__ () self.name = namec = C ('sherry') print (c. Inheritance classes _) # c object's attribute list print (c. Examples examples classrooms _) # c object's class print (C. Inheritance classes _) # the base class of class C, print (C. inheritance classes _) # the inheritance relationship of class C (C. inheritance subclassrooms _) # subclass output of class C: {'name':' sherry'} ( Shallow and deep copies of) (,) objects
Assignment operation of variable
It just forms two variables, which actually point to the same object.
Shallow copy Python
Copies are usually shallow copies. When copying, the sub-object contents contained by the object are not copied. Therefore, the source object and the copy object refer to the same child object.
Deep copy use
Use the deepcopy function of the copy module to recursively copy the sub-objects contained in the object. All children of the source object and the copy object are also different.
# Test shallow copy and deep copy import copyclass MobilePhone (): def _ _ init__ (self, cpu, screen): self.cpu = cpu self.screen = screenclass CPU (): def caculate (self): print ('cpu:\ tcopy self) class Screen (): def show (self): print (' screen:\ tcopy self) M1 = MobilePhone (CPU () Screen () print ('test assignment -') M0 = m1print ('M1:\ THERMOGRAPHY M1) m1.cpu.caculate () m1.screen.show () print ('M0:\ THANGLING M0) m0.cpu.caculate () m0.screen.show () print ('test shallow copy -') m2 = copy.copy (M1) print ('M1:\ THERONIMENTHAND M1) m1.cpu.caculate () print () m1.screen.show () M2) m2.cpu.caculate () m2.screen.show () print ('Test Deep copy -') m3 = copy.deepcopy (M1) print ('M1:\ tcopy M1) m1.cpu.caculate () m1.screen.show () print ('m3:\ t' M3) m3.cpu.caculate () m3.screen.show () output: test assignment-M1: cpu: screen: M0: cpu: screen: test shallow replication-M1: cpu: screen: m2: cpu: screen: test deep replication-M1: cpu: screen: m3: cpu: screen: combination
"is-a" relationship, we can use "inheritance". To implement the methods and properties of the parent class owned by the subclass. A "is-a" relationship refers to a relationship like this: a dog is an animal, dog is animal. Dogs should inherit animals.
In the "has-a" relationship, we can use "composition", or we can implement that one class has the methods and properties of another class. The "has-a" relationship refers to the relationship in which the phone has CPU. MobilePhone has a CPU .
Design pattern _ factory pattern implementation
Design pattern is a unique content of object-oriented language, and it is a fixed practice when we are faced with a certain kind of problem. there are many kinds of design patterns, the more popular one is: GOF (Goup Of Four) 23 design patterns. Of course, it is not necessary for us to learn all of them, but to learn a few commonly used ones.
For beginners, we learn the two most commonly used patterns: factory mode and singleton mode.
The factory pattern separates the creator from the caller, using special factory classes to select implementation classes and create objects for unified management and control.
# Test factory mode class CarFactory (): def creatCar (self Brand): if brand = 'Mercedes-Benz': return Benz () elif brand = = 'BMW': return BMW () elif brand = = 'BYD': return BYD () else: print ('can not createurs') class Benz (): passclass BMW (): passclass BYD (): passfactory = CarFactory () C1 = factory .creatCar ('Mercedes-Benz') c2 = factory.creatCar ('BMW') c3 = factory.creatCar ('BYD') design pattern _ singleton pattern implementation
The core role of the singleton pattern (Singleton Pattern) is to ensure that there is only one instance of a class and to provide a global access point to that instance.
The singleton pattern generates only one instance object, which reduces the overhead on system resources. When the generation of an object requires more resources, such as reading configuration files and generating other dependent objects, it can generate a "singleton object" and then permanently reside in memory, thus greatly reducing overhead.
# Test singleton mode class MySingleton (): _ _ obj = None _ _ init_flag = True def _ _ new__ (cls, * args, * * kwargs): if cls.__obj = = None: cls.__obj = object.__new__ (cls) # _ obj object is the Mysingleton object return cls.__obj def _ init__ (self) Name): if self.__init_flag = = True: print ('init....') Self.name = name self.__init_flag = Falsea = MySingleton ('aa') b = MySingleton (' bb') c = MySingleton ('cc') print (a) print (a.name) print (b) print (b.name) print (c) print (c.name) output: integration of init....aaaaaa factory mode and singleton mode # mixed use of test factory mode and singleton mode class CarFactory (): _ _ obj = None _ init_flag = True def _ _ new__ (cls * args, * * kwargs): if cls.__obj = = None: cls.__obj = object.__new__ (cls) return cls.__obj def _ _ init__ (self): if self.__init_flag: print ('init factory') self.__init_flag = False def creatCar (self Brand): if brand = 'Mercedes-Benz': return Benz () elif brand = = 'BMW': return BMW () elif brand = = 'BYD': return BYD () else: print ('can not createurs') class Benz (): passclass BMW (): passclass BYD (): passfactory = CarFactory () C1 = factory .creatCar ('Mercedes-Benz') c2 = factory.creatCar ('BMW') c3 = factory.creatCar ('BYD') factory2 = CarFactory () print (factory) print (factory2) output: init factory Thank you for reading! This is the end of this article on "what are the object-oriented features in Python?". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.