SoFunction
Updated on 2024-11-17

Python Object-Oriented Section Summary

This article is an example of Python object-oriented part of the knowledge. Shared for your reference, as follows:

Object-oriented:

Everything in this world can be categorized. -------------------- cell phones "-------------- a certain classification

Everything in the world is an object. -------------------- my cell phone "--------- has specific pointers to the

As long as it is an object, it must belong to some category.

As long as it's an object, it must have attributes.

The similarities of the classes are written together and the differences are written separately.

The source of self in the class:

Normally functions are executed as:

Calling a function - "Executing a function ----" returns the result of the execution of the function (gets a memory address)

This is not how methods in Python classes are executed.

Instead, the name of the current object is passed in while the object is instantiated. Then in the class __init__ need a parameter to accept the object, so the choice of self, self on behalf of the current object reference, pointing to the same memory address, so do not need to use return return value.

2. Why do methods in a class have at least one self parameter?

This is due to the methods in the class are coexisting (shared) within the class, unlike other field attributes that are copied in memory each time, but you have to know who the object is each time the method is called, and you need to pass the object that calls the method to the method, so you need a self to receive the object. At the bottom, this is accomplished through the ---- class. Methods (object names) implement this process. The final implementation is that whoever calls the method passes himself to the method. Class Name. Method name (object of the class)

r=Role('WFB') Role is a class with a got_shot() method.

r.got_shot()======" is essentially Role.got_shot(r)

3. Initialize in the constructor: open a space in memory and store some values. Methods that are not initialized in the constructor are in the memory of the class, not in the memory space of the instance.

Class and instance variables

Class variables can be accessed through both instances and classes, this is because the order of access is to access the instance first by default, or to access the class if it is not present in the instance.

Instance variables can be added and removed, as reflected:

4.1 Increase

4.1.1 Classes are initialized by taking the self parameter in the constructor __init__() and assigning it as follows.

class Role:
  def __init__(self, name):
    # Do some class initialization at instantiation time
     = name # essentially = name instance variable (static attribute), the scope is the instance itself

Substance for:

r=Role("wfb")===>r=Role(r, "wfb") and then assign in the constructor via =name.

4.1.2 Separately after the class instance, a new instance variable scope is now added only for that instance.

Example:

r=Role("wfb")
="Male."

The essence of the above two are the same, only the time of assignment is different, one is in the class in the instantiation (call the constructor) when the assignment. One is assigned after the instantiation and then in the assignment operation. The same can be achieved for the purpose of adding attributes to an instance.

4.2 Delete

Delete instance variables (just for the current object).

The way is =>

 del 

This leaves the instance without that variable, but does not affect other instance variables.

5. Is it possible to change class variables in a class in an instance?

class Role:
n="I am a class variable."
  def __init__(self, name):
    # Do some class initialization at instantiation time
     = name # essentially = name instance variable (static attribute), the scope is the instance itself
r1=Role("wfb")
="I'm a modified variable."
Print("===%s"%) #=====> output I'm the modified variable

r2=Role("WFB Nice")
Print("===%s"%) #======> The output is I am a class class variable.
# First look in the instance to see if there is an n, and if there isn't, look in the class to see if there is one.

Summarize: As we can see from the experiment, when we modify a variable with the same name in a class through an instance, we essentially add a new instance variable with the same name as the class variable in the memory of the instance. When other instances call the class variable in the class, the value of the class variable remains unchanged.

6. Is it possible to modify the class variables of a class directly through the class? Class name. Class variable == value],

The conclusion is: if there is a new instance with the same name as the class variable, then the value of the variable is the value of the variable in the instance, otherwise it is the value of the modified class variable, this is due to the order of access is the default first access to the instance, and if there is no instance, then come to access the class.

Note that if the variable is a list, modifying one affects them all, because they share the same memory address.

Instance variables are used to differentiate between each object, while class variables are shared by the instance objects used in the class. When an object instance needs a different value for this class variable, a new instance variable with the same name as the class variable can be added for that object instance.

7. private properties, private methods =====" reflects encapsulation

Format for:

Private attribute: __attr

Private method: def __way(self): pass

Characteristics: can only be accessed in the modified class, if the external need for private attributes or methods, the solution is to define a method inside the class that can be accessed externally, and then call the private attributes or methods in that method.

8. Inheritance

Inheritance refers to the ability to use all the functionality of an existing class and to extend that functionality without having to rewrite the original class.

There are 2 main types of implementations of the concept of inheritance: implementation inheritance, and interface inheritance.

Implementing inheritance is the ability to use the properties and methods of a base class without additional coding.

Interface inheritance means that only the names of attributes and methods are used, but subclasses must provide the ability to implement them (subclasses refactor the methods of the parent class).

8.1 Class Inheritance

8.1.1 Definition of succession

class Person(object):  # Define a parent class
  def talk(self):  # Methods in the parent class
    print("person is talking....") 
class Chinese(Person):  # Define a subclass that inherits the Person class #
  def walk(self):   # Define its own methods in subclasses
    print('is walking...')
c = Chinese()
()   # Call the methods of the inherited Person class
()   # Calling its own methods

exports

person is talking....
is walking...

8.1.2 Inheritance of constructors

 If we want to pass a parameter to instance c, we have to use a constructor, so how should the constructor be inherited, and also how to define its own attributes in a subclass?

Inherit the constructor method of the class:

1. The classic way to write a class: Parent class name. __init__(self, parameter 1, parameter 2, ...)

2. New style class writing: super(subclass, self). __init__(parameter 1, parameter 2, ....)

class Person(object):
  def __init__(self, name, age):
     = name
     = age
  def talk(self):
    print("person is talking....")
class Chinese(Person):
  def __init__(self, name, age, language): # Inherit first, refactor later
    Person.__init__(self, name, age) # Inherit the constructor method of the parent class, which can also be written as: super(Chinese,self). __init__(name,age)
     = language  # Define the class's own attributes
  def walk(self):
    print('is walking...')
class American(Person):
  pass
c = Chinese('wfb', 22, 'Chinese')

To summarize: If you simply define a constructor in the subclass Chinese, you are actually refactoring. This way the class can't inherit the properties of the parent class. So when we define a constructor for a subclass, we have to inherit first and then construct, so that we can also get the properties of the parent class.

The subclass constructor base parent constructor procedure is as follows:

Instantiate object c ---- > c call subclass __init__() ---- > subclass __init__() inherits parent __init__() ----- > call parent __init__()

8.1.3 Inheritance of parent class methods

If we need to modify a method of the base/parent class, we can refactor the method in the subclass. The talk() method as below.

class Person(object):
  def __init__(self, name, age):
     = name
     = age
  def talk(self):
    print("person is talking....")
class Chinese(Person):
  def __init__(self, name, age, language): 
    Person.__init__(self, name, age) 
     = language
    print(, , )
  def talk(self): # Subclasses Refactoring methods
    print('%s is speaking chinese' % )
  def walk(self):
    print('is walking...')
c = Chinese('wfb', 22, 'Chinese')
()

exports

wfb is speaking chinese

About multiple inheritance is in accordance with the inheritance from left to right [code to mention the way], in the inheritance of the existence of a sequential relationship, in which the constructor will inherit only one (from left to right whoever has the first inheritance).

Example:

class A:
  def __init__(self):
    print("A")
class B(A):
  def __init__(self):
    print("B")

class C(A):
  def __init__(self):
    print("C")
 
class D(B, C):
  pass

d = D()
# The result is output as B

Special:

 

9. Polymorphism: multiple implementations of an interface. Role: interface reuse.

Learn git for/FelixBinCloud/PythonLearn/tree/master/PythonLearn

Readers interested in more Python related content can check out this site's topic: thePython Object-Oriented Programming Introductory and Advanced Tutorials》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniques》、《Summary of Python coding manipulation techniquesand thePython introductory and advanced classic tutorials

I hope that what I have said in this article will help you in Python programming.