In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-06 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
In this article, the editor introduces in detail "how to use Python3 object-oriented technology". The content is detailed, the steps are clear, and the details are handled properly. I hope this article "how to use Python3 object-oriented technology" can help you solve your doubts.
Object-oriented has three main characteristics: encapsulation, inheritance and multi-attitude. Python has been an object-oriented language since the beginning of its design. Because of this, it is easy to create a class and object in Python.
Brief introduction of object-oriented Technology
Class: used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to each object in the collection. Object is an instance of a class. Method: the function defined in the class. Class variables: class variables are common to the entire instantiated object. Class variables are defined in the class and outside the function body. Class variables are not usually used as instance variables. Data members: class variables or instance variables are used to process data related to a class and its instance objects. Method rewriting: if a method inherited from the parent class does not meet the needs of the subclass, it can be overwritten. This process is called method override, also known as method rewriting. Local variable: a variable defined in a method that acts only on the class of the current instance. Instance variable: in the class declaration, the attribute is represented by a variable, which is called an instance variable, and an instance variable is a variable modified with self. Inheritance: a derived class (derived class) inherits the fields and methods of the base class (base class). Inheritance also allows an object of a derived class to be treated as a base class object. For example, there is a design: an object of type Dog is derived from the Animal class, which simulates the "is a (is-a)" relationship (example, Dog is an Animal). Instantiation: create an instance of a class, a concrete object of the class. Object: an instance of a data structure defined by a class. The object includes two data members (class variables and instance variables) and methods. Compared with other programming languages, Python adds a class mechanism without adding new syntax and semantics as much as possible.
Classes in Python provide all the basic functions of object-oriented programming: the inheritance mechanism of the class allows multiple base classes, derived classes can override any method in the base class, and methods with the same name can be called in the base class.
Objects can contain any amount and type of data.
Class definition
The syntax format is as follows:
Class ClassName:. . .
After the class is instantiated, you can use its properties, and in fact, after you create a class, you can access its properties through the class name.
Class object
Class objects support two operations: property reference and instantiation.
Property references use the same standard syntax as all property references in Python: obj.name.
After the class object is created, all names in the class namespace are valid property names. So if the class definition is like this:
Instance (Python 3.0 +) #! / usr/bin/python3class MyClass: "" A simple class instance "" I = 12345 def f (self): return 'hello world'# instantiation class x = MyClass () # access class properties and methods print ("MyClass class properties I are:", x.I) print ("method f output of the MyClass class is:", x.f ())
The above creates a new class instance and assigns the object to an object with an empty local variable xPowerx.
The output result of executing the above program is:
The attribute I of the MyClass class is: the method f of the 12345MyClass class is output as: hello world
The class has a special method (constructor) called init (), which is called automatically when the class is instantiated, like this:
Def _ init__ (self): self.data = []
The class defines the init () method, and the instantiation of the class automatically calls the init () method. The following instantiates the class MyClass, and the corresponding init () method is called:
X = MyClass ()
Of course, the init () method can have parameters, which are passed to the class instantiation operation through init (). For example:
Instance (Python 3.0 +) #! / usr/bin/python3class Complex: def _ init__ (self, realpart, imagpart): self.r = realpart self.i = imagpartx = Complex (3.0,4.5) print (x.r, x.i) # output result: 3.0-4.5self represents an instance of a class, not a class
There is only one special difference between methods of a class and ordinary functions-they must have an extra first parameter name, which by convention is self.
Class Test: def prt (self): print (self) print (self.__class__) t = Test () t.prt ()
The execution result of the above example is:
_ _ main__.Test
It is clear from the execution results that self represents an instance of the class and represents the address of the current object, while self.class points to the class.
Self is not a python keyword, and we can change it to runoob:
Class Test: def prt (runoob): print (runoob) print (runoob.__class__) t = Test () t.prt ()
The execution result of the above example is:
Methods of the _ _ main__.Test class
Inside the class, use the def keyword to define a method. Unlike the general function definition, the class method must contain the parameter self, which is the first parameter, and self represents an instance of the class.
Instance (Python 3.0 +) #! / usr/bin/python3# class definition class people: # define basic property name =''age = 0 # define private property, private property cannot be accessed directly outside the class _ _ weight = 0 # define constructor def _ _ init__ (self,n,a W): self.name = n self.age = a self.__weight = w def speak (self): print ("% s says: I am% d." % (self.name,self.age)) # instantiation class p = people ('runoob',10,30) p.speak ()
The output result of executing the above program is:
Runoob said: I am 10 years old. Inherit
Python also supports class inheritance, which is meaningless if a language does not support inheritance. The definition of a derived class is as follows
Class DerivedClassName (BaseClassName1):. . .
You need to pay attention to the order of the base class in parentheses. If there is the same method name in the base class and is not specified when the subclass is used, python searches from left to right, that is, if the method is not found in the subclass, find whether the base class contains the method.
BaseClassName (the base class name in the example) must be defined in the same scope as the derived class. In addition to classes, you can also use expressions, which is useful when the base class is defined in another module:
Class DerivedClassName (modname.BaseClassName): instance (Python 3.0 +) #! / usr/bin/python3# class definition class people: # define basic attribute name =''age = 0 # define private attribute, private attribute cannot be accessed directly outside the class _ _ weight = 0 # define constructor def _ _ init__ (self,n,a W): self.name = n self.age = a self.__weight = w def speak (self): print ("% s says: I am% d." % (self.name,self.age)) # single inheritance example class student (people): grade =''def _ init__ (self,n,a,w,g): # call the constructor of the parent class people.__init__ (self,n,a,w) self.grade = g # override the method of the parent class def speak (self): print ("% s says: I am% d years old I am reading% d grade "% (self.name,self.age,self.grade)) s = student ('ken',10,60,3) s.speak ()
The output result of executing the above program is:
Ken said: I'm 10 years old. I'm in the third grade.
Python also has limited support for multiple inheritance forms. A multi-inherited class definition looks like the following example:
Class DerivedClassName (Base1, Base2, Base3):. . .
You need to pay attention to the order of the parent class in parentheses. If the parent class has the same method name and is not specified when the subclass uses it, python searches from left to right, that is, if the method is not found in the subclass, it looks from left to right to see if the parent class contains the method.
Instance (Python 3.0 +) #! / usr/bin/python3# class definition class people: # define basic property name =''age = 0 # define private property, private property cannot be accessed directly outside the class _ _ weight = 0 # define constructor def _ _ init__ (self,n,a W): self.name = n self.age = a self.__weight = w def speak (self): print ("% s says: I am% d." % (self.name,self.age)) # single inheritance example class student (people): grade =''def _ init__ (self,n,a,w,g): # call the constructor of the parent class people.__init__ (self,n,a,w) self.grade = g # override the method of the parent class def speak (self): print ("% s says: I am% d years old I am reading% d grade "% (self.name,self.age,self.grade)) # another class, preparation before multiple inheritance class speaker (): topic =''name =' 'def _ _ init__ (self,n,t): self.name = n self.topic = t def speak (self): print (" my name is% s, I am an orator The theme of my speech is% s "% (self.name,self.topic)) # multiple inheritance class sample (speaker,student): a =''def _ _ init__ (self,n,a,w,g,t): student.__init__ (self,n,a,w,g) speaker.__init__ (self,n,t) test = sample (" Tim ", 25pd80 (4)," Python ") test.speak () # method has the same name The method that precedes the parent class in parentheses is called by default
The output result of executing the above program is:
My name is Tim. I am an orator. The theme of my speech is Python method rewriting.
If the function of your parent method does not meet your needs, you can override the method of your parent class in the subclass. the example is as follows:
Instance (Python 3.0 +) #! / usr/bin/python3class Parent: # define parent class def myMethod (self): print ('call parent method') class Child (Parent): # define subclass def myMethod (self): print ('call subclass method') c = Child () # subclass instance c.myMethod () # subclass invocation rewriting method super (Child C) .myMethod () # calling the method super () function that the parent class has been overridden with the subclass object is a method used to call the parent class (superclass).
The output result of executing the above program is:
Call subclass methods call parent class properties and methods
Private properties of the class
* * private_attrs: start with two underscores, declaring that the attribute is private and cannot be used or directly accessed outside the class. Self.**private_attrs when used in methods within a class.
Methods of the class
Inside the class, use the def keyword to define a method. Unlike the general function definition, the class method must contain the parameter self, which is the first parameter, and self represents an instance of the class.
The name of self is not required to die, and you can use this, but it is best to use self as agreed.
Private methods of the class
* * private_method: start with two underscores and declare the method to be a private method, which can only be called inside the class, not outside the class. Self.**private_methods .
Example
Examples of private properties of the class are as follows:
Instance (Python 3.0 +) #! / usr/bin/python3class JustCounter: _ secretCount = 0 # private variable publicCount = 0 # public variable def count (self): self.__secretCount + = 1 self.publicCount + = 1 print (self.__secretCount) counter = JustCounter () counter.count () counter.count () print (counter.publicCount) print (counter.__secretCount) # error, instance cannot access private variable
The output result of executing the above program is:
122Traceback (most recent call last): File "test.py", line 16, in print (counter.__secretCount) # reported an error. The instance cannot access the private variable AttributeError: 'JustCounter' object has no attribute' _ _ secretCount'
An example of a private method for a class is as follows:
Instance (Python 3.0 +) #! / usr/bin/python3class Site: def _ _ init__ (self, name, url): self.name = name # public self.__url = url # private def who (self): print ('name:', self.name) print ('url:' Self.__url) def _ foo (self): # Private method print ('this is a private method') def foo (self): # Public method print ('this is a public method') self.__foo () x = Site ('Rookie tutorial' 'www.runoob.com') x.who () # normal output x.foo () # normal output x.__foo () # error report
The execution result of the above example:
The proprietary methods of the
Init: constructor, call del: destructor when generating objects, use repr: print when releasing objects, convert setitem: assign values according to index getitem: get values according to index len: get length cmp: compare operation call: function call add: add operation sub: subtract operation mul: multiplication operation truediv: division operation mod: remainder operation pow: multiplier
Operator overloading
Python also supports operator overloading. We can overload the proprietary methods of the class. Examples are as follows:
Instance (Python 3.0 +) #! / usr/bin/python3class Vector: def _ init__ (self, a, b): self.a = a self.b = b def _ str__ (self): return 'Vector (% d,% d)'% (self.a, self.b) def _ add__ (self,other): return Vector (self.a + other.a, self.b + other.b) v1 = Vector (2Y10) v2 = Vector (5) -2) print (v1 + v2)
The execution result of the above code is as follows:
Vector (7Jing 8) read here, this "how to use Python3 object-oriented technology" article has been introduced, want to master the knowledge of this article also need to practice and use in order to understand, if you want to know more related articles, welcome to pay attention to the industry information channel.
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.