Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The calling method of python-- class attribute

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

This is a very common method of testing. A quick look at the methods used by class calls.

Consider an example:

Directory structure:

We are now going to call the class in class_learn. py in the file do_class.py

Code (do_class.py):

#!/ usr/bin/env python3#coding=utf-8'''@Author:Jock'''from all_python_learn.class_and_funcation.class_learn import *b = Learn(1,2)b.get()print(Learn.a)

Here we import the class from the module class_learn, instantiate an object of b through the class instantiation, and then call the get function in the class through the object b. Here I added print(Learn.a) to say that you can call variables of a class directly by appending the class name to the variable name.

Run Results:

What happens if we don't instantiate direct calls? take a look at

Modify do_class.py to:

If you write that, you're wrong because there's no instantiation.

Error:

The above example is a class with parameters passed in, but there can also be a class without parameters and then called.

Change class_learn.py to the following:

In do_class.py you can write:

Run Results:

Through the above example, basically know how to call the functions in the class, the variables in the class (this is very important, when writing use cases, you often cross files to access the attributes in the class!!)

But I guess you look at the above code after self is more confused, in fact, the beginning of the definition of the class has said, this is a must write, is an instance of the class.

The initialization function in the example

self.x=x #where x and y are instance variables self.y=y

This defines two variables x and y, and assigns them to the instances self.x and self.y. If you want to use these two variables in all later functions, you need to call them by writing self.x, and the parameter list of the function must have self, and the instance is passed in. Otherwise, the call will report an error.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report