home PYTHONJAVA
 

Python3 Object Orientation

Python has been an object-oriented language since its inception, and because of this, it's easy to create a class and object in Python. In this chapter we will detail Python's object-oriented programming.

If you haven't touched an object-oriented programming language before, you may need to understand some basic features of an object-oriented language and form a basic object-oriented concept in your mind, which will help you learn Python more easily. Object-Oriented Programming.

Next, let's take a brief look at some of the basic features of the following objects.


Introduction to Object-Oriented Technology

  • Class: is used to describe a collection of objects with the same properties and methods. It defines the properties and methods that are common to every object in the collection. An object is an instance of a class.
  • Method: The function defined in the class.
  • Class variables: Class variables are common throughout the instantiated object. Class variables are defined in the class and outside the body of the function. Class variables are usually not used as instance variables.
  • Data members: Class variables or instance variables are used to process related data for a class and its instance objects.
  • Method rewriting: If the method inherited from the parent class does not meet the needs of the subclass, you can rewrite it. This process is called override of the method, also known as the weight of the method. write.
  • Local variables: Variables defined in methods that only apply to classes of the current instance.
  • Instance variables: In a class declaration, attributes are represented by variables. Such variables are called instance variables and are declared inside the class declaration but outside of the other member methods of the class.
  • Inheritance: A derived class inherits the fields and methods of the base class. Inheritance also allows objects of a derived class to be treated as a base class object. For example, there is a design in which a Dog type object is derived from the Animal class, which simulates an "is-a" relationship (example, Dog is an Animal).
  • Instantiate: Create an instance of a class, a concrete object of the class.
  • Object: An instance of a data structure defined by a class. An object consists of two data members (class variables and instance variables) and methods.

Compared to other programming languages, Python adds class mechanisms without adding new syntax and semantics.

Classes in Python provide all the basic functionality of object-oriented programming: the inheritance mechanism of a class allows multiple base classes, and the derived class can override any method in the base class, and methods can call methods of the same name in the base class.

Objects can contain any number and type of data.


The

syntax is as follows:

class ClassName : <statement-1> . . . <statement-N>

After a class is instantiated, its properties can be used. In fact, after a class is created, its properties can be accessed through the class name.

class object

The

class object supports two operations: property reference and instantiation.

Property references use the same standard syntax as all property references in Python: obj.name.

After a class object is created, all naming in the class namespace is a valid property name. So if the class definition is like this:

Instance (Python 3.0+)

#!/usr/bin/python3 class MyClass: """A simple class instance """ i= 12345 def f(self): return 'hello world' # Instantiation Class x= MyClass() # Accessing class properties and methods print("The property i of the MyClass class is:", x.i) print("The method f output of the MyClass class is:", x.f())

The above creates a new class instance and assigns the object to a local variable x, x is an empty object.

Execute the above program output:

MyClass The attributes of the class< /span> i for:  12345
MyClass method of class f Export as: hello world

The

class has a special method called __init__() (constructor) that 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 class MyClass is instantiated as follows, and the corresponding __init__() method is called:

x = MyClass()

Of course, the __init__() method can have arguments, and the arguments are passed to the instantiation operation of the class via __init__() . E.g:

Instance (Python 3.0+)

#!/usr/bin/python3 class Complex: def __init__(self, realpart, imagpart)< /span>: self.r = realpart self.i = imagpart x= Complex(3.0, -4.5) print(x.r, x.i) # Output: 3.0 -4.5

self represents an instance of a class, not a class

The

class methods have a special difference from ordinary functions -- they must have an extra first parameter name, which by convention has the name self .

class Test : def prt(self): print(self) print(self.__class__) t= Test() t.prt()

The above example execution result is:

<__main__.Test instance at 0x100771878>
__main__.Test

From the execution results, it is obvious that self represents an instance of a class, representing the address of the current object, and self.class points to the class.

self is not a python keyword, and we can replace it with welookups:

class Test : def prt(welookups): print(welookups) print(welookups.__class__) t= Test() t.prt()

The above example execution result is:

<__main__.Test instance at 0x100771878>
__main__.Test

class method

Inside the class, use the def keyword to define a method. Unlike the general function definition, the class method must contain the parameter self, and the first parameter, self represents An instance of a class.

Instance (Python 3.0+)

#!/usr/bin/python3 #Class Definition class people: #Define basic attributes name = '' age = 0 #Define private properties, private properties are not directly accessible outside the class __weight = 0 #Define constructor def __init__(self,n,a,< /span>w): self.name = n self.age = a self.__weight = w def speak(self): print("%s says: I am %d old." %(self.name,self.age)) # Instantiation Class p = people('welookups',10, 30) p.speak()

Execute the above program output:

welookups said: I 10 Year. 

inherit

Python also supports inheritance of classes. If a language does not support inheritance, the class has no meaning. The definition of a derived class is as follows:

class DerivedClassName (BaseClassName1): <statement-1> . . . <statement-N>

Need to pay attention to the order of the base classes in parentheses. If the base class has the same method name and is not specified when the subclass is used, python searches from left to right. That is, when the method is not found in the subclass, it finds whether the method is included in the base class from left to right.

BaseClassName (the base class name in the example) must be defined in a scope with the derived class. In addition to classes, you can also use expressions, which are useful when the base class is defined in another module:

class DerivedClassName(modname.BaseClassName< /span>):

Instance (Python 3.0+)

#!/usr/bin/python3 #Class Definition class people: #Define basic attributes name = '' age = 0 #Define private properties, private properties cannot be accessed directly outside the class __weight = 0 #Defining the constructor def __init__(self,n,a,w): self.name = n self.age = a self.__weight = w def speak(self): print("%s Say: I am %d old." %(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 #Overriding the parent class def speak(self): print("%s Say: I %d Years old,I am reading %d grade"%(self.name,self.age,self.grade)) s = student('ken',10,60,3) s.speak()

Execute the above program output:

ken said: I 10 Year, I am reading 3 Year

Multiple inheritance

Python also has limited support for multiple inheritance forms. The multi-inherited class definition is as follows:

class DerivedClassName (Base1, Base2, Base3): <statement-1> . . . <statement-N>

Need to pay attention to the order of the parent classes in parentheses. If the parent class has the same method name and is not specified when the child class is used, python searches from left to right. That is, when the method is not found in the subclass, it searches from left to right whether the parent class contains a method.

Multiple inheritance

Python also has limited support for multiple inheritance forms. The multi-inherited class definition is as follows:

class DerivedClassName (Base1, Base2, Base3): <statement-1> . . . <statement-N>

Need to pay attention to the order of the parent classes in parentheses. If the parent class has the same method name and is not specified when the child class is used, python searches from left to right. That is, when the method is not found in the subclass, it searches from left to right whether the parent class contains a method.

Instance (Python 3.0+)

#!/usr/bin/python3 #Single inheritance example class student(people): grade = '' def __init__(self,n,a,w,g): #The single inheritance example calls the constructor of the parent class.... people.__init__(self,n,a,w) self.grade = g #Overriding the parent class def speak(self): print("%s Say: I am %d old, I am reading %d grade"%(self.name,self.age,self.grade)) #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",25,80,4,"Python") test.speak() #The method name is the same, the default method is to call the parent class in the parentheses.

The proprietary method of the class:

  • __init__ : Constructor, called when generating an object
  • __del__ : Destructor, used when releasing objects
  • __repr__ : Print, convert
  • __setitem__ : Assign by index
  • __getitem__: Get values by index
  • __len__: Get length
  • __cmp__: Comparison Operations
  • __call__: function call
  • __add__: Addition
  • __sub__: Subtraction
  • __mul__: Multiplication operation
  • __truediv__: divide operations
  • __mod__: Residual operations
  • __pow__: Power

operator overloading

Python also supports operator overloading. We can override the class's proprietary methods, as shown in the following example:

Instance(Python 3.0+)

#!/usr/bin/python3 class 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(2,10) v2 = Vector(5,-2) print (v1 + v2)





welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.