[21-day python punch card] Object-oriented programming on the 7th day (2)

Hits: 0

​Hello everyone, today is the 7th day of the 21-day python punch card. The [last article] talked about python ‘s knowledge [of object-oriented] programming, what a class is, and the three elements of object-oriented. Today we will talk about how python creates classes, abstract classes, and instructions on access restrictions.

Event address: CSDN 21-day Learning Challenge

The biggest reason for learning is to get rid of mediocrity, one day earlier, one more wonderful life; one day later, one more day of mediocrity .

Table of contents

create class

Create a class:

Use of class objects

abstract class

Abstract class concept:

abc module in python

restriction of visit

Why restrict access

Access restrictions by defining private properties

Access restrictions by defining private functions;

Special case:

reflection mechanism

what is reflex mechanism

create class

First, we create a class, the example is below.

Create a class:

# -*- coding: UTF-8 -*-

from random import choice

class Divergence:

    def __init__(self,name='robot'):
        self.name = name
        pass

    def  getChoice ( self ,name=None) :
         if name is not  None: 
            self .name = name
         self .__lists = [ 'scissors' , 'rock' , 'cloth' ]
        result = choice(self.__lists)
        print( self .name, ': selected >' ,result)

When defining a class, if  the init () constructor is not manually added, or there is only one self parameter in the added  init (), the parameters when creating a class object can be omitted.

In the above code, since the constructor also includes the name parameter in addition to the self parameter, and the default parameter is set, when instantiating the class object, pass in the corresponding name value as needed (the self parameter is a special parameter and does not need to be Manually pass the value, Python will automatically pass it the value)

Use of class objects

A defined class cannot be used until it is instantiated, that is, an object is created using that class. In general, an instantiated class object can do the following:

Access or modify instance variables owned by class objects, and even add new instance variables or delete existing instance variables;
call methods of class objects, including calling existing methods, and dynamically adding methods to class objects.

The following acceptance how to use:

#Pass the name parameter when instantiating the object
d = Divergence('A')
d.getChoice()

#Instantiate without passing parameters
d = Divergence()

#Pass d.getChoice('A') when calling the method

We use examples to illustrate how to create objects.

To create a point object, there are many ways to create an instance of a class. We call a point where the x, y, and z of a point are the same as the diagonal point.

</p> <h1>-<em>- coding: UTF-8 -</em>-</h1> <p>class Point : # TODO(You): Add code to support class creation</p> <p>if <strong>name</strong> == '<strong>main</strong>': points = []</p> <pre><code># TODO(You): Create 1000 diagonal points in batches, the coordinates of the i-th point are (i,i,i) for point in points: print(point) </code></pre> <p>

You can complete the code like this

class Point: def <strong>init</strong>(self, x, y, z): self.x = x self.y = y self.z = z</p> <p>if <strong>name</strong> == '<strong>main</strong>': points = [] for i in range(1000): points.append(Point(i,i,i))

abstract class

Abstract class concept:

  • An abstract class is a special class. Its special feature is that it can only be inherited and cannot be instantiated. It needs to be implemented with the help of python modules;
  • Abstract classes are extracted from a bunch of classes with the same content, including data attributes and function attributes.
  • The difference between an abstract class and an ordinary class is that there are abstract methods in an abstract class, the class cannot be instantiated, but can only be inherited, and subclasses must implement abstract methods

abc module in python

  • Python needs to use the abc module to implement abstract classes

  • The essence of an abstract class is still a class, which refers to the similarity of a group of classes, including data attributes (such as all_type) and function attributes;

  • Abstract class is a concept between class and interface, and has some features of class and interface at the same time

The following describes the concept of abstract classes through specific python topics

Use abc library, create abstract BasePoint class, create Point subclass, implement dot abstract method, calculate inner product

</p> <h1>-<em>- coding: UTF-8 -</em>-</h1> <p>import abc</p> <h1>TODO(You): Please implement the abstract class BasePoint</h1> <p>class Point(BasePoint): def <strong>init</strong>(self, x, y, z) -> None: super().<strong>init</strong>(x, y, z)</p> <pre><code>def dot(self, right): return self.x*right.x+self.y*right.y+self.z*right.z </code></pre> <p>if <strong>name</strong> == '<strong>main</strong>': p1 = Point(0, 1, 2) p2 = Point(2, 4, 6) assert p1.dot(p2) == 16 p1 = BasePoint(0, 1, 2) p2 = BasePoint(2, 4, 6) assert p1.dot(p2) is None

Completion code is as follows

class BasePoint: def <strong>init</strong>(self, x, y, z) -> None: self.x = x self.y = y self.z = z</p> <pre><code>@abc.abstractmethod def dot(self, right): pass </code></pre> <p>

restriction of visit

Why restrict access

Doing access restrictions is for the robustness of the program. If the important properties in the function can be arbitrarily modified from the outside, it is possible that the program will crash just because of an inadvertent parameter modification.

  • Access restrictions by defining private properties

By default, an object’s properties are externally accessible. To make the property inaccessible from outside the object, define the property as private.
Private properties can only be accessed through accessor methods
Python does not provide direct support for private properties, to make a method or property private (not accessible from the outside), simply start its name with two underscores

class Apple(): 
    def name(self,name):
       self.__name = name

    def getName(self):
        return self.__name

  • Access restrictions by defining private functions;

Like properties, private functions can be implemented by adding two underscores before the function name;

class Apple(): 
    def __setAge(self,age):
       self.__age = age

    def getName(self):
        return self.__name

    def info(self,age):
        self.__setAge(age);

  • Special case:

In Python, variables that start with a double underscore and end with a double underscore are special variables such as name, which can be accessed directly;
according to convention, the name of an instance variable starting with an underscore (such as _category) External It can also be accessed directly, but this form of variable means, “Although I can be accessed, please treat me as a private variable and don’t access it at will”

[reflection] mechanism

what is reflex mechanism

Using reflection in Python can get all the properties of an object, this mechanism is called reflection (which in turn lets the object tell us what it is), and is used to obtain information about an unknown object at runtime.

  • Python has several built-in methods that can be used to inspect or access properties of objects. These methods can be used on arbitrary objects;

dir([obj]):

Calling this method will return a list containing most of obj’s property names (there will be some special properties not included). The default value of obj is the current module object.

harvesttr(obj, attr):

This method is used to check if obj has an attribute with a value named attr, returning a boolean value.

getattr(obj, attr):

Calling this method will return the value of the attribute named attr value in obj,

setattr(obj, attr, val):

Calling this method will assign val to the attribute of obj’s value named attr.

type(obj)

To determine the object type, use the type() function

That’s all for today, and in the next article, we’ll talk about the basic skills of python.

You may also like...

Leave a Reply

Your email address will not be published.