An Initial Exploration of Object-Oriented Programming in Python

Keywords: Python Attribute Java Programming


Many people come into contact with Python from crawlers. In fact, many languages can be crawlers, but Python is simpler than other languages.But Python is more than just a crawler; it is more widely used in artificial intelligence, scientific computing, and so on.Ancient Cloud: Wan Zhang Tall Building rises flat, in order to have considerable development, it is very important to lay a good foundation. This paper mainly explains the object-oriented knowledge of Python, which is only for learning and sharing. If there are any deficiencies, please also correct them.

Object-oriented features

  • Class: A collection of features that describe the same thing, such as the Person class, which represents a person and has attributes and characteristics of a person.
  • Object: A specific instance defined by a class, such as: zhangsan represents a specific person.
  • Inheritance: A derived class inherits the methods and properties of a base class and has its own properties and characteristics, such as Man being a subclass of Person.
  • Encapsulation: Hides data and implementation details and provides external access.
  • Polymorphism: A class that can have multiple derived classes and can have different forms.
  • Abstract: The process of focusing only on the essential features, regardless of the details.

These are the basic features of object-oriented, so how does Python do with object-oriented?

Create Class


As follows:

  • Use the class statement to create a new class followed by the name of the class and ending with a colon.
  • Python's classes, which do not have braces to indicate the scope of the class's content, are indented.
  • The difference between a member method of a class and a normal method is that the first parameter of the method definition is self, which represents an instance of the class, but is not required when called.
  • Where uInit_uThe method is the init ialization method of the class, which is called when the object is declared.
  • Where uDel_uThe method is a destructor and is called when the class is released.
 1 class Employee:
 2     """Employee Class"""
 3     emp_count = 0  # A variable is a class variable whose value will be shared among all instances of this class
 5     def __init__(self, name, salary):
 6         """Initialization"""
 7 = name
 8         self.salary = salary
 9         Employee.emp_count += 1
11     def display_count(self):
12         """Display quantity"""
13         print('Total Employee =', Employee.emp_count)
15     def display_employee(self):
16         """display information"""
17         print('name =',, ', salary = ', self.salary)
19     def prt(self):
20         """Print yourself"""
21         print(self)
22         print(self.__class__)
24     def __del__(self):
25         """Destructor"""
26         print(self, 'Released')

create object

Python creates objects without the need for a new keyword, similar to function calls, and different from Java and.Net.As follows:

1 'Create the first object'
2 emp = Employee('Jack', 20)
3 emp.display_count()
4 emp.display_employee()
5 emp.prt()

Dynamic Add and Delete Object Properties

Object properties can be added dynamically, unlike compiled languages, as follows:

1 emp.age = 17  # Add one 'age' attribute
2 emp.age = 28  # modify 'age' attribute
3 del emp.age  # delete 'age' attribute

You can also add and get attributes using Python's built-in methods, as follows:

1 print(getattr(emp, 'name'))  # get attribute
2 print(hasattr(emp, 'age'))  # Whether to include attributes
3 setattr(emp, 'age', 18)  # Setting properties and values
4 print(hasattr(emp, 'age'))  # Whether to include attributes
5 print(getattr(emp, 'age'))  # get attribute
6 delattr(emp, 'age')  # Delete Properties
7 print(hasattr(emp, 'age'))  # Whether to include attributes

Python also has some properties of built-in classes, as follows:

1 # Built-in Objects
2 print("Employee.__doc__:", Employee.__doc__)
3 print("Employee.__name__:", Employee.__name__)
4 print("Employee.__module__:", Employee.__module__)
5 print("Employee.__bases__:", Employee.__bases__)
6 print("Employee.__dict__:", Employee.__dict__)

Properties and methods of classes

  • Private properties of a class, starting with a double underscore, can only be accessed through self within the class.
  • The protected property of a class, starting with an underscore, allows only subclasses and calls to itself.
  • Inside a class, a method can be defined for a class using the def keyword. Unlike a general function definition, a class method must contain the parameter self and be the first parameter
  • Private method of a class: Starts with two underscores and declares that the method is private and cannot be called outside the class.Call self. u inside a classPrivate_Methods

As follows:

1 class JustCounter:
2     """Class Description"""
3     __secretCount = 0  # Private variable of class
4     publicCount = 0  # Open Variables
6     def count(self):
7         self.__secretCount += 1
8         self.publicCount += 1
9         print('Private variables:', self.__secretCount)

Python does not allow instantiated classes to access private data, but you can use object. _ClassName_uAttrName (object name.)_Class Name_uPrivate property name) Access properties as follows:

1 print(counter._JustCounter__secretCount)


Class Inheritance

One of the main benefits of object-oriented programming is code reuse, which is achieved through inheritance mechanisms.New classes created by inheritance are called subclasses or derived classes, and inherited classes are called base classes, parent classes, or superclasses.

  • Inheritance in Python is implemented in the form of a class subclass name (parent class name):
  • Subclasses can invoke methods of the parent class and define their own methods.
  • If the functionality of the parent method is not sufficient, the subclass can override the method of the parent.

Parent represents a parent class and has its own properties and methods.

 1 class Parent:
 2     """Define Parent Class"""
 3     parentAttr = 100
 5     def __init__(self):
 6         print('Call the parent class's constructor')
 8     def parentMethod(self):
 9         print('Call parent method')
11     def setAttr(self, attr):
12         Parent.parentAttr = attr
14     def getAttr(self):
15         print('Parent Properties:', Parent.parentAttr)
17     def myMethod(self):
18         print('I am a parent MyMethod')

Child represents a subclass that inherits from Parent as follows:

 1 class Child(Parent):
 2     """Define subclasses"""
 4     def __init__(self):
 5         print('Call the construction method of the subclass')
 7     def childMethod(self):
 8         print('Call subclass methods')
10     def myMethod(self):
11         """Rewrite Overrides Parent Method"""
12         print('I am a subclass MyMethod')
14     def __str__(self):
15         """Rewrite method, suitable for reading"""
16         return 'str Method Return'

Instantiation of subclasses

As follows:

1 c = Child()  # Instantiate Subclass Object
2 c.childMethod()  # Call subclass methods
3 c.parentMethod()  # Call parent method
4 c.setAttr(200)  # Call the parent method again to set properties
5 c.getAttr()  # Call parent method again to get properties
6 c.myMethod()  # Called on a subclass MyMethod


You can use built-in functions to determine the relationship between subclasses and classes as follows:

1 print(issubclass(Child, Parent))  # Determine whether the parent-child relationship corresponds
2 print(isinstance(c, Child))  # Determine if it is an instance object
3 print(isinstance(c, Parent))  # Determine if it is an instance object



autumn thoughts

Author: Ma Zhiyuan

Willow old tree dumb crow, small bridge water family, old road westerly thin horse.At sunset, people with broken bowels are everywhere.

Posted by pleisar on Mon, 08 Jun 2020 11:20:42 -0700