1. Description of the error
2. Reasons for reporting errors
As you can see from the error code, I have two classes involved here, which I'll describe using Class A and Class B.
Class A: a method class under which get_element(), which reported the error, is a method.In that class I did not instantiate the
Class B: A's get_element() method is called in get_element().Only at the beginning from A import A.
Since class A is not instantiated, I didn't instantiate class B. I just introduced the class directly. So my final call is actuallyClass A directly calls the class method get_element() . So it reported an error.
3. Solutions
There are two solutions:
3.1 Instantiation
In class A we instantiate, for example :a = A()
.
Then the instantiated object of class A is introduced in class B instead of A as a class. Example:from A import a
If you want to call a method of class A, the call is made as follows:a.get_element(pass parameter)
3.2 Adding the modifier @classmethod
What this modifier does:
1, @classmethod declare a class method, and for the usual we see is called instance method.
2, the first parameter of the class method cls (abbreviation of class, referring to the class itself), while the first parameter of the instance method is self, indicating an instance of the class
3, can be called through the class, like (), equivalent to the java static method '''''
Example:
class A(object): # attribute defaults to a class attribute (which can be given to be called directly by the class itself) num = "Class Attributes" # Instantiation methods (must instantiate class before being called) def func1(self): # self : denotes the address id of the instantiated class print("func1") print(self) # Class methods (which can be called by the class itself without instantiating it) @classmethod def func2(cls): # cls : indicates that the class itself is not instantiated. print("func2") print(cls) print() cls().func1() # Do not pass a method that passes the default self parameter (the method is also directly callable by the class, but it is not standard to do so) def func3(): print("func3") print() # Properties are directly callable from the class itself # A.func1() This call is an error: because func1() needs to be called with the address id parameter of the instantiated class by default, and cannot be called without instantiating the class A.func2() A.func3()
Then for my example, add the modifier @classmethod directly in front of the method get_element() to be called for class A:
The code will be able to run successfully.
summarize
The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.