In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "what is the use of Python namedtuple". In the operation of actual cases, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1: tell me about your understanding of modules and packages in Python.
Each Python file is a module, and the folder where these files are saved is a package, but this folder as a Python package must have a file named _ _ init__.py, otherwise the package cannot be imported. Usually there can be subfolders under a folder, which means that there can also be subpackages under a package, and the _ _ init__.py in the subpackage is not required. Modules and packages solve the problem of naming conflicts in Python. Different packages can have modules with the same name, and different modules can have variables, functions or classes with the same name. You can use import or from in Python. Import... To import packages and modules, you can also use the as keyword to alias packages, modules, classes, functions, variables, etc., so as to completely solve the problem of naming conflicts in programming, especially in the development of multi-person collaborative teams.
2: tell me about the Python coding specification that you know.
Comments: the enterprise's Python coding specification is basically developed with reference to PEP-8 or Google open source project style guide, the latter also mentioned that you can use Lint tools to check the standard level of the code, when you encounter such problems during the interview, you can first talk about these two reference standards, and then focus on the matters needing attention in Python coding.
The use of spaces
Use spaces to indicate indentation instead of using tabs (Tab).
Each level of indentation associated with grammar is represented by four spaces.
The number of characters per line should not exceed 79 characters, and if the expression is too long to occupy multiple lines, all lines except the first line should add 4 spaces to the normal indentation width.
The definitions of functions and classes are separated by two blank lines before and after the code.
In the same class, methods should be separated by a blank line.
A space should be left on the left and right sides of the binary operator, and only one space should be fine.
Identifier naming
Variables, functions, and properties should be spelled in lowercase letters, and if there are multiple words, underscores should be used to connect them.
Protected instance properties in the class should start with an underscore.
Private instance properties in the class should start with two underscores.
Classes and exceptions should be named with the first letter of each word capitalized.
Module-level constants should be in all uppercase letters, and if there are more than one word, connect with an underscore.
Class, the first parameter should be named self to represent the object itself.
Class, the first parameter should be named cls to represent the class itself.
Expressions and statements
Use inline negative words instead of putting negative words in front of the whole expression. For example, if an is not b is easier to understand than if not an is b.
Instead of checking the length to determine whether a string, list, etc., is None or has no elements, check it as if not x.
Even if there is only one line of code in the if branch, for loop, except exception catch, etc., do not write the code with if, for, except, etc., separate will make the code clearer.
The import statement is always placed at the beginning of the file.
When introducing modules, from math import sqrt is better than import math.
If you have multiple import statements, you should divide them into three parts, Python standard modules, third-party modules, and custom modules from top to bottom, and each part should be arranged alphabetically according to the name of the module.
3: whether running the following code will report an error, if you report an error, please indicate what kind of error there is, and if you do not report an error, please state the execution result of the code.
Class A:
Def _ _ init__ (self, value):
Self.__value = value
@ property
Def value (self):
Return self.__value
Obj = A (1)
Obj.__value = 2
Print (obj.value)
Print (obj.__value)
Comments: there are two points in this question, one is the understanding of the object attribute access permissions starting with _ and _ _ and the @ property decorator, and the other is the understanding of dynamic language, which does not need too much explanation.
one
two
Extension: if you don't want the code to dynamically add new properties to the object at runtime, you can use the _ _ slots__ magic when defining the class. For example, we can add a line _ _ slots__ = ('_ value',) to the above A, and run the above code again, and an AttributeError error will be generated at line 10.
4: sort the dictionaries given below by the values from largest to smallest.
Prices = {
'AAPL': 191.88
'GOOG': 1186.96
'IBM': 149.24
'ORCL': 48.44
'ACN': 166.89
'FB': 208.09
'SYMC': 21.29
}
Comments: the high-level use of the sorted function often occurs during the interview. The key parameter can be passed in a function name or a Lambda function, and the return value of this function represents the basis for comparing elements in sorting.
Sorted (prices, key=lambda x: prices [x], reverse=True)
Topic 45: talk about the usage and function of namedtuple.
Comments: the collections module of the Python standard library provides many useful data structures, which are not clear to every developer, such as the namedtuple asked in the questions. In the interviews I have attended, 90% of the interviewees can not accurately describe its role and application scenarios. In addition, deque is also a very useful but often overlooked class, as well as Counter, OrderedDict, defaultdict, UserDict and so on. Do you know their usage?
When using an object-oriented programming language, defining classes is the most common thing. Sometimes, we use classes with only properties but no methods. This kind of objects are usually only used to organize data and cannot receive messages. So we call this class a data class or a degenerate class, just like a structure in C language. We do not recommend using this degenerate class, which can be replaced with namedtuple (named tuple) in Python.
From collections import namedtuple
Card = namedtuple ('Card', (' suite', 'face'))
Card1 = Card ('hearts', 13)
Card2 = Card ('grass flower', 5)
Print (f'{card1.suite} {card1.face}')
Print (f'{card2.suite} {card2.face}')
Named tuples are immutable containers like ordinary tuples. Once the data is stored in the top-level attributes of namedtuple, the data can no longer be modified, which means that all attributes on the object follow the principle of "write once, read multiple times". Unlike ordinary tuples, the data in named tuples has access names, and the saved data can be obtained by name rather than index, which is not only easier to operate, but also more readable to the code.
A named tuple is essentially a class, so it can also be used as a parent class to create a subclass. In addition, named tuples have a series of built-in methods. For example, named tuples can be treated as dictionaries through the _ asdict method, or shallow copies of named tuple objects can be created through the _ replace method.
Class MyCard (Card):
Def show (self):
Faces = [', 'Agar,' 2,'3,'4,'5,'6,'7,'8,'9,'10,'J,'Q,'K']
Return f'{self.suite} {faces [self.face]} 'print (Card) #
Card3 = MyCard ('diamonds', 12)
Print (card3.show ()) # Square Q
Print (dict (card1._asdict () # {'suite':' hearts', 'face': 13}
Print (card2._replace (suite=' box')) # Card (suite=' box', face=5) "what is the use of Python namedtuple" is introduced here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.