Super detailed description of Class (class) in python
Class
Used to describe theSame properties and methodsofCollection of objects. It defines the properties and methods common to each object in the collection.Objects are instances of classes。
A person (height: 1.8 meters) needs to eat, drink water, and sleep;
A tiger (weight: 300 catties) has to run, bathe, and hunt.
1. Noun definition
- Class:A collection of objects that describe the same properties and methods. It defines the properties and methods common to each object in the collection. An object is an instance of a class.
- method:Functions defined in the class.
-
Class variables:Class variables are common throughout the instantiated object.
- General location: Class variables are defined in the class and outside the function body.
- Inherent propertiesRepresented by class variables.
- Class variables are not usually used as instance variables.
- Modifications to class variables will affect all instances of the class.
- Data Members:Class variables or instance variables are used to process related data of classes and their instance objects.
- Method rewrite:If a method inherited from the parent class cannot meet the needs of the subclass, it can be rewritten. This process is called override of method, also known as override of method.
-
Instance variables:
- General location: in class
__init__
In the statement. - Attributes are represented by variables, which are called instance variables, and are generallyCustom properties。
- General location: in class
-
Local variables:
- General position: variables defined in the method.
- Classes that only work on the current instance (object).
- Once the function or method is executed, local variables will be destroyed.
- Local variables have nothing to do with the class itself, and local variables can be found in methods defined inside or outside the class.
- inherit:That is, a derived class inherits the properties and methods of the base class. Inheritance also allows objects of a derived class to be treated as a base class object.
-
Instantiation:Create an instance of a class, that is, create a specific object of a class.
- The instance can change or delete the original attribute.
- Object:Data structure instances defined by class,An instance is an object. An object consists of two data members (class variables and instance variables) and methods.
2. Take a sneak peek
Common examples:
#Preferred examples:Define a person(male)Want to have a meal、Drink water、sleep; There is a specific person now,He was given the above definition,So he's a man,Can eat,会Drink water,会sleep。 #Class name: One person#Attribute: Male#Method: Eat, drink water, sleep#Object: This specific person (the process of giving this person the same attributes and methods is called "instance")
-
none
__init__
Code example (there are__init__
Will write later):class Calculator: # Calculator: Class Name name = 'Good calculator' # name: class variable (inherent property) price= 18 # price: class variable (inherent properties) def add(self,x, y): # add(): method result=x+y # result: local variables print(result) def minus(self, x, y): # minus(): Method result=x-y # result: local variables print(result) def times(self, x, y): # times(): Method print(x*y) def divide(self, x, y): # divide(): method print(x/y) cal1 = Calculator() # ☆Instantiation (cal1 also has the same properties and methods)———————————————————————————————————————————————————————————————————————————————————————————— >>> ----->'Good calculator' >>> (1,2) ----->3 >>> ----->18 >>> =25 >>> ----->25 # The attributes of the instance can be modified
3. Detailed explanation
(1)self
When defining a method with def, the first parameter must be self .
-
self represents an instance (object) of a class, essentially representing the address of the current object, not a class; but points to a class.
Please see VCR:
class Test: def prt(self): print(self) print(self.__class__) t = Test() () ———————————————————————————————————————————————————————————————————————————————————————————— #The output result is (result of two prints):<__main__.Test instance at 0x100771878> __main__.Test
self is not a python keyword, you can change it to other words, but it is still highly recommended to use self.
(2) Method
- Inside the class, usedefKeywords to define a method.
- Unlike general functions, a class method must contain the parameter self when defining it, and is the first parameter. Self represents an instance of the class.
- self is not a keyword in python, so you can use other words instead of self .
But as usual, it is best to use self.
def add(self,x,y) # add is the method name, and x and y are the parameters that need to be entered to call this function result=x+y
__init__
A built-in method, which can be called "construction method", initialization (the abbreviation of Initialize)
Two underlines in front and back
It will be called automatically during instantiation to initialize custom properties
-
have
__init__
Code example (the default custom attribute is not given, it needs to be given manually when instantiating):One thing to note in the code below is that the custom properties are high, not hig, and hig is just input parameters.
class Calculator: # Calculator: Class Name class_variable = "I am a class variable" # This is a class variable (inherent property) name = 'Good calculator' # name: class variable (inherent property) price= 18 # price: class variable (inherent properties) #***************************** def __init__ (self, hig, wid, wei): # * = hig # high: instance variable (custom attribute) * = wid # width: instance variable (custom attribute) * = wei # weight: instance variable (custom attribute) * #***************************** def add(self,x, y): # add(): method result=x+y # result: local variables print(result) def minus(self, x, y): # minus(): Method result=x-y # result: local variables print(result) def times(self, x, y): # times(): Method print(x*y) def divide(self, x, y): # divide(): method print(x/y) ———————————————————————————————————————————————————————————————————————————————————————————— #Run the program first>>> cal2 = Calculator(1,5,12) #When instantiating, be sure to give the content of the custom attribute>>> ----->'Good calculator' >>> ----->1 >>> (1,2) ----->3 >>> ----->18 >>> =25 >>> ----->25 # The inherent and customized properties of the instance can be modified
-
have
__init__
Code example (given the default custom attribute):...#Same as above #******************* def __init__ (self, hight=1, width=5, weight=12): * = hight # high: Custom properties * = width # width: Custom properties * = weight # weight: Custom properties * #******************* ...#Same as above———————————————————————————————————————————————————————————————————————————————————————————— #Run the program first>>> cal2 = Calculator() #When instantiating, no need to give custom properties, unless you want to modify
-
super().__init__()
Functions and usageIn Python, the super() function is a method used to call the parent class (superclass). The constructor in the class (
__init__
) Used in )super().__init__()
is a common practice (especially in the case of multiple inheritance, which ensures that the parent class is initialized correctly, but here is not a lot about multiple inheritance).
————
The super() function of python3 is in this format, which is more streamlined than the super() function of python2.-
usage:
Suppose we have a base class (parent class) and a derived class (subclass). When the subclass is initialized, it may require some already set properties or methods of the parent class. We want to be initialized when the subclass is initialized.Initialize base class as well. You can use it now
super().__init__()
。 -
Example:
class Parent: def __init__(self, name): = name print(f"Parent with name: {}") class Child(Parent): def __init__(self, name, age): super().__init__(name) # Call the __init__ method of the parent class = age print(f"Child with name: {} and age: {}") # Use subclasseschild_instance = Child("Alice", 10) --------------------------------------------------------------------------------------------------------------- # Run resultsParent with name: Alice Child with name: Alice and age: 10
Used here
f-string
Characters, if you are interested, you can search online or ask GPT directly.
-
__call__
A built-in method with two underscores in front and back.
This built-in method is a bit too much, but it has some wonderful uses that need to be experienced slowly...
The function of this built-in function is:
"Instances can be used directly as functions, and their effect is__call__
The effect of the function”, at this time,__call__
The input parameters of the function are the input parameters of the instance.
For specific usage code, see the following running program results:
class Calculator: # Calculator: Class Name class_variable = "I am a class variable" # This is a class variable (inherent property) name = 'Good calculator' # name: class variable (inherent property) price= 18 # price: class variable (inherent properties) #***************************** def __init__ (self, hig, wid, wei): # * = hig # high: instance variable (custom attribute) * = wid # width: instance variable (custom attribute) * = wei # weight: instance variable (custom attribute) * #***************************** def __call__ (self, test_value): print("Output is:" + str(test_value)) def add(self,x, y): # add(): method result=x+y # result: local variables print(result) ———————————————————————————————————————————————————————————————————————————————————————————— #Run the program first>>> cal2 = Calculator(1,5,12) #When instantiating, be sure to give the content of the custom attribute>>> ----->'Good calculator' >>> cal2(111) -----> Output is:111
Add one more mouth: the call methods of the other self-named methods (functions) areInstance name. Method name()
。
(3) Inheritance
It means that you first define a benchmark class, and then you want to define a derivative class. The derived class wants to use the properties and methods of the benchmark class. This process of adoption is called "inheritance".
A subclass (derived class DerivedClassName) inherits the properties and methods of the parent class (baseClassName).
-
Single inheritance:
-
When the base class and the derived class are in the same module:
class Derived class names(Base class name): ... Code block ...
-
When the base class and the derived class are not in the same module, you need to import the base class from the module where the base class is located:
-
Writing method 1 (importing only base class):
#Assuming the base class BaseClassName is in the module modnamefrom modname import BaseClassName class DerivedClassName(BaseClassName): ... Code block ...
-
Write method 2 (directly import the module where the base class is located):
#Assuming the base class BaseClassName is in the module modnameimport modname class DerivedClassName(): ... Code block ...
-
Example:
#Class definitionclass people: #Define basic properties name = '' age = 0 #Define private attributes, private attributes cannot be accessed directly outside the class __weight = 0 #Define the constructor def __init__(self,n,a,w): = n = a self.__weight = w def speak(self): print("%s said: I am %d." %(,)) #Single Inheritance Exampleclass student(people): grade = '' def __init__(self,n,a,w,g): #Calling the parent class's composition people.__init__(self,n,a,w) = g #Methods to overwrite parent class def speak(self): print("%s said: I am %d and I am studying %d grade"%(,,)) s = student('ken',10,60,3) () ———————————————————————————————————————————————————————————————————————————————————————————— #The output result is:ken explain: I 10 It's old,I在读 3 grade
-
-
Multiple inheritance:
#Reference, basically no need:/python3/
(4) Method rewriting
If the function of the method defined by the parent class does not meet the requirements, you can override the method of the parent class in the subclass.
Example:
class Parent: # Define the parent class def myMethod(self): print ('Call parent class method') class Child(Parent): # Define subclasses def myMethod(self): print ('Call the subclass method') c = Child() # Subclass instance() # Subclass calls to rewrite methodssuper(Child,c).myMethod() #Calling methods whose parent class has been overwritten with subclass objects———————————————————————————————————————————————————————————————————————————————————————————— #The output result is:Calling subclass methods Call parent class method
4. GPT explanation of instance variables, local variables, and class variables
In Python's inheritance mechanism, it is very important to understand instance variables, local variables, and class variables. These variables vary in scope and life cycles in classes and their objects. Here is a detailed explanation of these variables:
-
Instance Variables
Instance variables are also called object variables, and they are variables defined in instances of a class (i.e. objects). Each instance has its own independent copy of instance variables, and even if two instances belong to the same class, their instance variable values can be different. Instance variables are usually constructed by class (
__init__
) to initialize.class MyClass: def __init__(self, value): self.instance_variable = value # This is an instance variable obj1 = MyClass(10) obj2 = MyClass(20) print(obj1.instance_variable) # Output: 10print(obj2.instance_variable) # Output: 20
-
Local Variables
Local variables are variables defined inside functions or methods. Their scope is limited to the functions or methods that define them. Once the function or method is executed, local variables will be destroyed. Local variables have nothing to do with the class itself, and local variables can be found in methods defined inside or outside the class.
class MyClass: def my_method(self): local_variable = "I am a local variable" # This is a local variable print(local_variable) obj = MyClass() obj.my_method() # Output: I am a local variable# Here, local_variable no longer exists
-
Class Variables
Class variables are variables defined at the class level and they do not belong to any specific instance of the class. Instead, they are shared by all instances of the class. Class variables can be accessed through the class itself or through any instance of the class. When modifying a class variable through an instance, this change affects all instances because all instances share the same class variable.
class MyClass: class_variable = "I am a class variable" # This is a class variable def __init__(self, value): self.instance_variable = value def print_variables(self): print(self.class_variable) # Access class variables through instances print(MyClass.class_variable) # Access class variables directly through class names # Modify class variablesMyClass.class_variable = "I have been modified" obj1 = MyClass(10) obj2 = MyClass(20) obj1.print_variables() # Output: I have been modified and I have been modifiedobj2.print_variables() # The output is the same as above, because the class variable is shared by all instances
Note: Although class variables can be accessed through instances, it is best to access and modify the class variables through the class name to avoid potential confusion. Especially when modifying class variables through instances, it is clear that doing so will affect the class variable values shared by all instances.
Summarize
This is all about this article about Class (class) in python. For more relevant python Class class description content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!
Related Articles
Summary of the method of remotely controlling Windows server in Python
In the torrent of the information age, mastering a programming language has become a must-have skill. Python, a programming language known for its simplicity, easy to learn and powerful, has become a great sword for countless developers. Today, what we are going to discuss is how to remotely control Windows servers with Python. Friends who need it can refer to it.2024-07-07A brief discussion on the use of () in tensorflow
Today, the editor will share with you a brief discussion on the use of () in tensorflow, which has good reference value and hope it will be helpful to everyone. Let's take a look with the editor2020-02-02Python's Pillow library performs image file processing (detailed explanation of the pictures and texts)
This article explains in detail the detailed process of using the Pillow library for simple processing of pictures, the detailed process of using PyCharm to develop Python, and the installation and use of various third-party libraries. If you are interested, please learn about it2021-11-11Python method to extract hyperlinks in web pages
Many people learn Python at the beginning and plan to use it for crawler development. Since you want to be a crawler, you must first crawl the web page and extract the hyperlink address from the web page. This article will share with you a simple method, and you can refer to it if you need it.2016-09-09Python-pandas returns index issue with duplicate data
This article mainly introduces the index problem of Python-pandas returning duplicate data. It has good reference value. I hope it will be helpful to everyone. If there are any errors or no complete considerations, I hope you will be very encouraged.2024-02-02ActiveMQ: How to access ActiveMQ using Python
Today, the editor will share with you an article on ActiveMQ: The method of using Python to access ActiveMQ is of great reference value and I hope it will be helpful to everyone. Let's take a look with the editor2019-01-01tkinter Disable (read-only) drop-down list Combobox issue
This article mainly introduces the problem of tkinter disable (read-only) drop-down list Combobox, which is of good reference value and hope it will be helpful to everyone. If there are any mistakes or no complete considerations, I hope you will be very grateful for your advice2023-01-01Python crawler interview book (FAQ)
This article mainly introduces the Python crawler interview book and a summary of common questions. Friends who need it can refer to it.2018-03-03The role of OpenCV in python and installation case tutorial
This article mainly introduces the role of OpenCV in python and the installation case tutorial. This article explains the understanding and use of this technology through brief cases. The following is the detailed content. Friends who need it can refer to it.2021-07-07python realizes residual quantity analysis of empirical modal decomposition of PyEMD
This article mainly introduces PyEMD empirical modal decomposition and variant residual analysis. Friends in need can refer to it for reference. I hope it can be helpful. I wish you more progress and get a promotion as soon as possible.2022-05-05