[Python] object oriented programming

Posted by bestpricehost on Sun, 19 Jan 2020 11:54:44 +0100

Article directory

1. Object oriented lead

Python has been an object-oriented language since the beginning of design. Because of this, it is easy to create a class and object in Python.

Next, let's briefly understand some basic features of the following object.

  • Class: a collection used to describe objects with the same properties and methods. It defines the properties and methods that are common to each object in the collection. Object is an instance of a class.
  • Class variable: class variable is common in the whole instantiated object. Class variables are defined in the class and outside the function body. Class variables are usually not used as instance variables.
  • Data member: a class variable or instance variable is used to process data related to a class and its instance objects.
  • Method overload: if the method inherited from the parent class cannot meet the requirements of the child class, it can be overridden. This process is called method override, also known as method overload.
  • Instance variable: the variable defined in the method, which only affects the class of the current instance.
  • Inheritance: a derived class inherits the fields and methods of the base class. Inheritance also allows the object of a derived class to be treated as a base class object. For example, there is a design where an object of type Dog is derived from an Animal class, which simulates an "is-a" relationship (for example, Dog is an Animal).
  • Instantiation: create an instance of a class, the specific object of the class.
  • Method: the function defined in the class.
  • Object: an instance of a data structure defined by a class. Object includes two data members (class variable and instance variable) and methods.

2. Creation of class

Create class

Use the class statement to create a new class, followed by the class name and ending with a colon, as shown in the following example:

class ClassName:
   'Help for class'   #Class document string
   class_suite  #Class body

The help information of the class can be viewed through classname. Doc.

class_suite consists of class members, methods, and data attributes.

Create an instance of a class

Here is a simple Python class instance:

#coding=utf-8
class Employee:
   'Base class for all employees'
   empCount = 0

   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1
   
   def displayCount(self):
     print "Total Employee %d" % Employee.empCount

   def displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary
  • The empCount variable is a class variable whose value will be shared among all instances of the class. You can use Employee.empCount access in internal or external classes.
  • The first method, the init method, is a special method called the class's constructor or initialization method, which is called when an instance of the class is created
  • Self represents an instance of a class. It is necessary for self to define a method of a class, although it is not necessary to pass in corresponding parameters when calling.

self represents an instance of a class, not a class

There is only one special difference between a class's methods and a normal function - 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 instance at 0x10d066878>
__main__.Test

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

Create instance object

To create an instance of a class, you can use the name of the class and accept parameters through the init method.

"Establish Employee First object of class"
emp1 = Employee("Zara", 2000)
"Establish Employee Second object of class"
emp2 = Employee("Manni", 5000)

Access attribute

You can use points (.) to access the properties of an object. Use the name of the following class to access class variables:

emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount

Complete example

class Employee:
   'Base class for all employees'
   empCount = 0

   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1
   
   def displayCount(self):
     print "Total Employee %d" % Employee.empCount

   def displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary

"Establish Employee First object of class"
emp1 = Employee("Zara", 2000)
"Establish Employee Second object of class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount

Output results:

Name :  Zara ,Salary:  2000
Name :  Manni ,Salary:  5000
Total Employee 2

You can add, delete, and modify the properties of a class as follows:

emp1.age = 7  # Add an 'age' attribute
emp1.age = 8  # Modify 'age' property
del emp1.age  # Delete 'age' attribute

You can also access properties using the following functions:

  • getattr(obj, name[, default]): access the properties of the object.
  • hasattr(obj,name): check if an attribute exists.
  • setattr(obj,name,value): set an attribute. If the property does not exist, a new property is created.
  • delattr(obj, name): delete attribute.
hasattr(emp1, 'age')    # Returns True if the 'age' property exists.
getattr(emp1, 'age')    # Returns the value of the 'age' property
setattr(emp1, 'age', 8) # Add attribute 'age' with a value of 8
delattr(empl, 'age')    # Delete attribute 'age'

Built in class properties

  • dict: properties of a class (including a dictionary, which consists of data properties of the class)
  • doc: document string of class
  • Name: class name
  • Module: the module where the class definition is located (the full name of the class is' main.className '. If the class is in an import module mymod, then className.module is equal to mymod)
  • bases: all the parent elements of a class (including tuples composed of all the parent classes)

Examples are as follows:

#coding=utf-8
#!/usr/bin/python

class Employee:
   'Base class for all employees'
   empCount = 0

   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1
   
   def displayCount(self):
     print "Total Employee %d" % Employee.empCount

   def displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary

print "Employee.__doc__:", Employee.__doc__
print "Employee.__name__:", Employee.__name__
print "Employee.__module__:", Employee.__module__
print "Employee.__bases__:", Employee.__bases__
print "Employee.__dict__:", Employee.__dict__

Output results:

Employee.__doc__: Base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount': <function displayCount at 0x10a939c80>, 'empCount': 0, 'displayEmployee': <function displayEmployee at 0x10a93caa0>, '__doc__': '\xe6\x89\x80\xe6\x9c\x89\xe5\x91\x98\xe5\xb7\xa5\xe7\x9a\x84\xe5\x9f\xba\xe7\xb1\xbb', '__init__': <function __init__ at 0x10a939578>}

3. Inheritance of class

inherit

One of the main benefits of object-oriented programming is code reuse. One of the ways to achieve this reuse is through inheritance mechanism. Inheritance can be understood as the type and subtype relationship between classes.

Note: inherited syntax class derived class name (base class name): / / The base class name is written in parentheses. The base class is specified in tuples when the class is defined.

Some features of inheritance in python:

  • 1: The construction of the base class (init() method) in inheritance will not be called automatically. It needs to be called specifically in the construction of its derived class.
  • 2: When calling the method of the base class, you need to prefix the class name of the base class and bring the self parameter variable. Unlike calling ordinary functions in classes, you don't need to bring self parameters.
  • 3: Python always finds methods of the corresponding type first. If it can't find the corresponding methods in the derived classes, it starts to find them one by one in the base classes. (first find the called method in this class, and then find it in the base class.).

If more than one class is listed in the inheritance tuple, it is called "multiple inheritance".

Syntax:

The declaration of derived classes is similar to their parent classes. The list of inherited base classes follows the class name as follows:

class SubClassName (ParentClass1[, ParentClass2, ...]):
   'Optional class documentation string'
   class_suite

Examples are as follows:

#coding=utf-8
#!/usr/bin/python

class Parent:        # Defining parent class
   parentAttr = 100
   def __init__(self):
      print "Call parent constructor"

   def parentMethod(self):
      print 'Call parent method'

   def setAttr(self, attr):
      Parent.parentAttr = attr

   def getAttr(self):
      print "Parent attribute :", Parent.parentAttr

class Child(Parent): # Defining subclasses
   def __init__(self):
      print "Call subclass constructor"

   def childMethod(self):
      print 'Call subclass method child method'

c = Child()          # Instantiation subclass
c.childMethod()      # Method of calling subclass
c.parentMethod()     # Call parent method
c.setAttr(200)       # Call the method of the parent class again
c.getAttr()          # Call the method of the parent class again

Output results:

Call subclass constructor
 Call child method
 Call parent method
 Parent property: 200

You can also inherit multiple classes, for example:

class A:        # Define class A
.....

class B:         # Define class B
.....

class C(A, B):   # Inherited classes A and B
.....

You can use the issubclass() or isinstance() methods to detect.

  • issubclass(): a Boolean function determines that a class is a subclass or descendant of another class. Syntax: issubclass(sub,sup)
  • isinstance(obj, Class): Boolean function returns true if obj is an instance object of Class or an instance object of a Class subclass

Method rewriting

If the function of your parent method cannot meet your needs, you can override your parent's method in the child class:

Examples are as follows:

#coding=utf-8
#!/usr/bin/python

class Parent:        # Defining parent class
   def myMethod(self):
      print 'Call parent method'

class Child(Parent): # Defining subclasses
   def myMethod(self):
      print 'Call subclass method'

c = Child()          # Subclass instance
c.myMethod()         # Subclass call override method

Output results:

Call subclass method

Method overloading

The following table lists some common functions that can be overloaded in your own class:

Serial number Method, description & simple call
1 init ( self [,args… ]) constructor simple call method: obj = className(args)
2 Del (self) destruct method, delete a simple calling method of object: del obj
3 Repr (self) is transformed into a simple call method for the interpreter to read: repr(obj)
4 Str (self) is a simple call method used to convert values into human readable forms: str(obj)
5 CMP (self, x) object: cmp(obj, x)

Operator overloading

Python also supports operator overloading. Examples are as follows:

#!/usr/bin/python

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

Output results:

Vector(7,8)

4. Class properties and methods

  • Private property of the class: "private attrs": two underscores start. It is declared private and cannot be used or directly accessed outside the class ground. Self. Private. Attrs when used in methods within a class.

  • Class method: in the class, you can define a method for the class by using the def keyword. Unlike the general function definition, the class method must contain the parameter self, which is the first parameter

  • Class's private method: "private method": it starts with two underscores, declaring that the method is private and cannot be called outside the class. Call self. Private methods inside the class

Examples are as follows:

#coding=utf-8
#!/usr/bin/python
class JustCounter:
	__secretCount = 0  # private variable
	publicCount = 0    # Open 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 reported, instance cannot access private variable

Output results:

1
2
2
Traceback (most recent call last):
  File "test.py", line 17, in <module>
    print counter.__secretCount  # Error reported, instance cannot access private variable
AttributeError: JustCounter instance has no attribute '__secretCount'

Python does not allow instantiated classes to access private data, but you can use object. \

.........................
print counter._JustCounter__secretCount

Execute the above code, and the execution result is as follows:

1
2
2
2

Single underline, double underline, head and tail double underline description

  • foo: special methods are defined, generally system defined names, such as init().
  • _foo: a variable of protected type is indicated by a single underscore, that is, the protected type can only be accessed by itself and its subclass, and cannot be used for from module import*
  • __foo: Double underscores represent variables of private type, which can only be accessed by the class itself.
246 original articles published, 121 praised, 10000 visitors+
Private letter follow

Topics: Python Attribute Programming