python learned function (d)

the hasattr () function (built-in function)

Reprinted from: https://blog.csdn.net/chituozha5528/article/details/78023463

hasattr (object, name)
determines whether an object name or attribute name inside method returns BOOL value, there is the name attribute returns True, otherwise return False.

Note that the name between braces

class test():
    name='xiaoming'
    def run(self):
        return 'Hello World!'
 
t=test()
print hasattr(t,"name")#输出True
print hasattr(t,"run")#输出True

Example:

 

 range()

Reprinted from: https: //blog.csdn.net/sinat_33588424/article/details/80206971 

python range () function creates a list of integers, generally used in a for loop.

Syntax: Range (Start, STOP [, STEP])
Start: start counting from the start. The default is zero. E.g. range (5) is equivalent to Range (0,. 5); 
stop: stop counting to the end, but not stop. For example: range (0, 5) is [0, 1, 2, 3, 4] No. 5 
STEP: step size, default is one. For example: range (0, 5) is equivalent to the range (0, 5, 1)
 

>>>range(10)        # 从 0 开始到 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)     # 从 1 开始到 11
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)  # 步长为 5
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)  # 步长为 3
[0, 3, 6, 9]
>>> range(0, -10, -1) # 负数
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]

 The following is the range for the use of the loop of each letter runoob:

>>>x = 'runoob'
>>> for i in range(len(x)) :
...     print(x[i])
... 
r
u
n
o
o
b
>>>

Reprinted from: https: //blog.csdn.net/littlehaes/article/details/82490884 

In python2, range () returns List, may be two range () added directly, such as range (10) + range (15) 
to python3 in, range () into a class, two not directly range () added directly, need add List, such as list (range (10)) +  list (range (10))
as in the range python3 () to save memory, only the memory range () to start, stop, step three elements, one by one when the remaining count value use, in fact, iterator, plus list () lets range () all values can be calculated by adding up
 

Only ()

Seek length string x, Python wording is len (x), and this also applies to the wording of the list, tuples, and dictionaries objects only need to pass the corresponding parameter. len () function is common.

Python uses a prefix expression

 

set()

forward from:

https://blog.csdn.net/yushupan/article/details/82698223

set is a combination does not allow duplicate content, and set the contents of the location is random, it is not listed in the index. The relationship may be tested, deduplication, can compute the intersection, difference, and sets the like.

1. Create a collection set

>>> set([1,2,3])
{1, 2, 3}
>>> set('123')
{'1', '2', '3'}
>>> set()
set() #创建一个空set
 

enumerate()

Reprinted from: https://blog.csdn.net/qq_18941425/article/details/79737438

1. There is a list = [1, 2, 3   , 4, 5, 6]
print output:
0 1 
1, 2, 
2, 3, 
3, 4, 
4,5 
5,6 

list=[1,2,3,4,5,6]
 
for i ,j in enumerate(list)
 
  print(i,j)

You can use enumerate the same time when the need and value index values.

word_to_idx = {w:i for i, w in enumerate(unique_vocab)}
#给unique_vocab中的词加一个序号标签:
    格式为w(词):i(序号) 
    进行循环将词和序号取出来:for i, w(enumerate中的两个变量) in enumerate()

argparse中add_argument

Reprinted from: https://blog.csdn.net/Samaritan_x/article/details/84146029

add_argument: When you run the program, given the parameters by calling the given parameters executor
ArgumentParser.add_argument (name or flags ... [, action] [, nargs] [, const] [, default] [, type] [, choices] [, required] [, help] [, metavar] [, dest])
 

name of flags is necessary parameter, which accepts option parameter or location parameter.
 

parser.add_argument('--inner-batch', help='inner batch size', choices=[1,5,10], default=5, type=int)

The above example will '--inner-batch', for example at startup demo.py, ./demo.py --inner-batch input terminal 10 will in the inner-batch This option parameter is set to 10, 5 does not use parameters to default parameters.

Nargs parameter defaults to a number, you can also set multiple ourselves.

When the option is specified or no to accept a parameter nargs = '?', When no parameters, will value from the default of. For there is an additional parameter options, the option that appears and is not followed, then the value will follow specific parameters in the const

type parameter type, e.g. int.

range of choices for selecting the input parameters, such as the above choices = [1,5,10] shows parameters can only be 1 or 5 or 10

required in order to set the display parameters, when required to True, the parameter that needs to be displayed when inputting a command

help to describe the effect of this option

This action indicates the operation to be performed option

dest specifies the location for the parameter

metavar information with help of the output

lambda

Reprinted from: https://blog.csdn.net/zjuxsl/article/details/79437563

 Format: lambda argument_list: expression

           argument_list is a list of parameters

           expression is an expression about the parameters

usage:

           lambda x, y: x * y; x is a function of the input and y, the output thereof is the product x * y

           lambda: None; function has no input parameters, output is None

           lambda * args: sum (args); arbitrary number of arguments is input, and the output thereof is the (implicit requirement is that the input parameters must be capable of adding)

           lambda ** kwargs: 1; any key-value is input parameters, output 1



sorted()

Reprinted from: https://blog.csdn.net/ymaini/article/details/81633775

A method for performing a sort operation sorted, list such as numbers, strings, according to the type of dict sort key or value, usually a method will now be sorted using the sort of data types and

sorted(iterable[, cmp[, key[, reverse]]])
    """
    对一个iterable对象排序,返回一个排序之后的list

    @param iterable 可迭代遍历对象
    @param cmp 默认None, 自定义的比较函数,2个参数
    @param key 默认None, 自定义的函数,1个参数,参数值来源与列表元素
    @param reverse 默认False(正序)
    @return 返回一个排序之后的list
    """
    pass

map () function

Reprinted from: https://blog.csdn.net/maoersong/article/details/21868037

You can view the map through the help Python () the specific usage

>>> help(map)

Help on built-in function map in module __builtin__:

map(...)
    map(function, sequence[, sequence, ...]) -> list
    
    Return a list of the results of applying the function to the items of
    the argument sequence(s).  If more than one sequence is given, the
    function is called with an argument list consisting of the corresponding
    item of each sequence, substituting None for missing values when not all
    sequences have the same length.  If the function is None, return a list of
    the items of the sequence (or a list of tuples if more than one sequence).

receiving a map and an iterative function object (such as a list) as a parameter, with each element of the processing function, and returns the new list.

Example 1:
 

>>> list1 = [1,2,3,4,5]

>>> map(float,list1)

[1.0, 2.0, 3.0, 4.0, 5.0]

>>> map(str,list1)

['1', '2', '3', '4', '5']

等价于

>>> list1

[1, 2, 3, 4, 5]

>>> for k in list1:

float(list1[k])


2.0

3.0

4.0

5.0

lower()

Reprinted from: https://blog.csdn.net/qq_40678222/article/details/83033422

Description: Converts all uppercase to lowercase string.

Syntax: str.lower () -> str Returns a string

str1 = "I Love Python"
str2 = "Groß - α" #德语 大写α
print(str1.casefold())
print(str1.lower())
print(str2.casefold())
print(str2.lower())

result:

i love python
i love python
gross - α
groß - α

Note  lower () function and casefold () function of the difference between:

lower () method only ASCII code, i.e., 'A-Z' valid, valid for the case to lower case to upper case conversion in other languages, only with casefold () function.

 

super()

Reprinted from: https://blog.csdn.net/qq_14935437/article/details/81458506

If the child class also defines _init_ () function, then how to call the base class _init_ () function:

A method, explicitly specify  :

class  C(P):
     def __init__(self):
             P.__init__(self)
             print 'calling Cs construtor'

The second method using the super () method  :

class  C(P):
    def __init__(self):
            super(C,self).__init__()
            print 'calling Cs construtor'
 
c=C()

The super Python () method is designed to look for problems to solve when multiple inheritance parent class, so do not matter in super single inheritance used; however, the use of super () is a good habit. It will be so generally use when we need to call the parent class method in a subclass.

The benefits of super () is to avoid using the name of the parent class is mainly used for multiple inheritance, as follows:

class A:
 def m(self):
  print('A')
 
class B:
 def m(self):
  print('B')
 
class C(A):
 def m(self):
  print('C')
  super().m()
 
C().m()

The advantage of this is: If you want to change the sub-class inherits the parent class (from A changed B), you only need to change one line of code (class C (A): -> class C (B)) can, without the need to find a large number of class C code, modify the base class name, on the other hand the code portability and reusability higher.

Also: Avoid using super (self .__ class__, self), under normal circumstances is not the problem, is the fear of extreme cases:
 

class Foo(object):
    def x(self):
        print 'Foo'
 
class Foo2(Foo):
    def x(self):
        print 'Foo2'
        super(self.__class__, self).x() # wrong
 
class Foo3(Foo2):
    def x(self):
        print 'Foo3'
        super(Foo3, self).x()
 
f = Foo3()
f.x()

super (self .__ class__, self) in Foo2 results in an infinite loop, never go to the next super class MRO Foo3 in the first argument super should always be the current class, Python does not specify how code must go write, but to develop some good habits is very important, you do not know will avoid a lot of problems.
 

Guess you like

Origin blog.csdn.net/weixin_40952784/article/details/90693555