日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python常见问题(2):编程问题 Programming FAQ

發布時間:2025/3/21 python 66 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python常见问题(2):编程问题 Programming FAQ 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Contents

  • Programming FAQ
    • General Questions
      • Is there a source code level debugger with breakpoints, single-stepping, etc.?
      • Is there a tool to help find bugs or perform static analysis?
      • How can I create a stand-alone binary from a Python script?
      • Are there coding standards or a style guide for Python programs?
      • My program is too slow. How do I speed it up?
    • Core Language
      • Why am I getting an UnboundLocalError when the variable has a value?
      • What are the rules for local and global variables in Python?
      • Why do lambdas defined in a loop with different values all return the same result?
      • How do I share global variables across modules?
      • What are the “best practices” for using import in a module?
      • Why are default values shared between objects?
      • How can I pass optional or keyword parameters from one function to another?
      • What is the difference between arguments and parameters?
      • Why did changing list ‘y’ also change list ‘x’?
      • How do I write a function with output parameters (call by reference)?
      • How do you make a higher order function in Python?
      • How do I copy an object in Python?
      • How can I find the methods or attributes of an object?
      • How can my code discover the name of an object?
      • What’s up with the comma operator’s precedence?
      • Is there an equivalent of C’s ”?:” ternary operator?
      • Is it possible to write obfuscated one-liners in Python?
    • Numbers and strings
      • How do I specify hexadecimal and octal integers?
      • Why does -22 // 10 return -3?
      • How do I convert a string to a number?
      • How do I convert a number to a string?
      • How do I modify a string in place?
      • How do I use strings to call functions/methods?
      • Is there an equivalent to Perl’s chomp() for removing trailing newlines from strings?
      • Is there a scanf() or sscanf() equivalent?
      • What does ‘UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)’ mean?
    • Sequences (Tuples/Lists)
      • How do I convert between tuples and lists?
      • What’s a negative index?
      • How do I iterate over a sequence in reverse order?
      • How do you remove duplicates from a list?
      • How do you make an array in Python?
      • How do I create a multidimensional list?
      • How do I apply a method to a sequence of objects?
      • Why does a_tuple[i] += [‘item’] raise an exception when the addition works?
    • Dictionaries
      • How can I get a dictionary to display its keys in a consistent order?
      • I want to do a complicated sort: can you do a Schwartzian Transform in Python?
      • How can I sort one list by values from another list?
    • Objects
      • What is a class?
      • What is a method?
      • What is self?
      • How do I check if an object is an instance of a given class or of a subclass of it?
      • What is delegation?
      • How do I call a method defined in a base class from a derived class that overrides it?
      • How can I organize my code to make it easier to change the base class?
      • How do I create static class data and static class methods?
      • How can I overload constructors (or methods) in Python?
      • I try to use __spam and I get an error about _SomeClassName__spam.
      • My class defines __del__ but it is not called when I delete the object.
      • How do I get a list of all instances of a given class?
      • Why does the result of?id()?appear to be not unique?
    • Modules
      • How do I create a .pyc file?
      • How do I find the current module name?
      • How can I have modules that mutually import each other?
      • __import__(‘x.y.z’) returns <module ‘x’>; how do I get z?
      • When I edit an imported module and reimport it, the changes don’t show up. Why does this happen?

General Questions

Is there a source code level debugger with breakpoints, single-stepping, etc.?

Yes.

The pdb module is a simple but adequate console-mode debugger for Python. It is part of the standard Python library, and is?documented?inthe?Library?Reference?Manual. You can also write your own debugger by using the code for pdb as an example.

The IDLE interactive development environment, which is part of the standard Python distribution (normally available as Tools/scripts/idle), includes a graphical debugger.

PythonWin is a Python IDE that includes a GUI debugger based on pdb. The Pythonwin debugger colors breakpoints and has quite a few cool features such as debugging non-Pythonwin programs. Pythonwin is available as part of the?Python for Windows Extensions?project and as a part of the ActivePython distribution (see?https://www.activestate.com/activepython).

Boa Constructor?is an IDE and GUI builder that uses wxWidgets. It offers visual frame creation and manipulation, an object inspector, many views on the source like object browsers, inheritance hierarchies, doc string generated html documentation, an advanced debugger, integrated help, and Zope support.

Eric?is an IDE built on PyQt and the Scintilla editing component.

Pydb is a version of the standard Python debugger pdb, modified for use with DDD (Data Display Debugger), a popular graphical debugger front end. Pydb can be found at?http://bashdb.sourceforge.net/pydb/?and DDD can be found at?https://www.gnu.org/software/ddd.

There are a number of commercial Python IDEs that include graphical debuggers. They include:

  • Wing IDE (https://wingware.com/)
  • Komodo IDE (https://komodoide.com/)
  • PyCharm (https://www.jetbrains.com/pycharm/)

Is there a tool to help find bugs or perform static analysis?

Yes.

PyChecker is a static analysis tool that finds bugs in Python source code and warns about code complexity and style. You can get PyChecker from?http://pychecker.sourceforge.net/.

Pylint?is another tool that checks if a module satisfies a coding standard, and also makes it possible to write plug-ins to add a custom feature. In addition to the bug checking that PyChecker performs, Pylint offers some additional features such as checking line length, whether variable names are well-formed according to your coding standard, whether declared interfaces are fully implemented, and more.https://docs.pylint.org/?provides a full list of Pylint’s features.

How can I create a stand-alone binary from a Python script?

You don’t need the ability to compile Python to C code if all you want is a stand-alone program that users can download and run without having to install the Python distribution first. There are a number of tools that determine the set of modules required by a program and bind these modules together with a Python binary to produce a single executable.

One is to use the freeze tool, which is included in the Python source tree as?Tools/freeze. It converts Python byte code to C arrays; a C compiler you can embed all your modules into a new program, which is then linked with the standard Python modules.

It works by scanning your source recursively for import statements (in both forms) and looking for the modules in the standard Python path as well as in the source directory (for built-in modules). It then turns the bytecode for modules written in Python into C code (array initializers that can be turned into code objects using the marshal module) and creates a custom-made config file that only contains those built-in modules which are actually used in the program. It then compiles the generated C code and links it with the rest of the Python interpreter to form a self-contained binary which acts exactly like your script.

Obviously, freeze requires a C compiler. There are several other utilities which don’t. One is Thomas Heller’s py2exe (Windows only) at

http://www.py2exe.org/

Another tool is Anthony Tuininga’s?cx_Freeze.

Are there coding standards or a style guide for Python programs?

Yes. The coding style required for standard library modules is documented as?PEP 8.

My program is too slow. How do I speed it up?

That’s a tough one, in general. There are many tricks to speed up Python code; consider rewriting parts in C as a last resort.

In some cases it’s possible to automatically translate Python to C or x86 assembly language, meaning that you don’t have to modify your code to gain increased speed.

Pyrex?can compile a slightly modified version of Python code into a C extension, and can be used on many different platforms.

Psyco?is a just-in-time compiler that translates Python code into x86 assembly language. If you can use it, Psyco can provide dramatic speedups for critical functions.

The rest of this answer will discuss various tricks for squeezing a bit more speed out of Python code.?Never?apply any optimization tricks unless you know you need them, after profiling has indicated that a particular function is the heavily executed hot spot in the code. Optimizations almost always make the code less clear, and you shouldn’t pay the costs of reduced clarity (increased development time, greater likelihood of bugs) unless the resulting performance benefit is worth it.

There is a page on the wiki devoted to?performance tips.

Guido van Rossum has written up an anecdote related to optimization at?https://www.python.org/doc/essays/list2str.

One thing to notice is that function and (especially) method calls are rather expensive; if you have designed a purely OO interface with lots of tiny functions that don’t do much more than get or set an instance variable or call another method, you might consider using a more direct way such as directly accessing instance variables. Also see the standard module?profile?which makes it possible to find out where your program is spending most of its time (if you have some patience – the profiling itself can slow your program down by an order of magnitude).

Remember that many standard optimization heuristics you may know from other programming experience may well apply to Python. For example it may be faster to send output to output devices using larger writes rather than smaller ones in order to reduce the overhead of kernel system calls. Thus CGI scripts that write all output in “one shot” may be faster than those that write lots of small pieces of output.

Also, be sure to use Python’s core features where appropriate. For example, slicing allows programs to chop up lists and other sequence objects in a single tick of the interpreter’s mainloop using highly optimized C implementations. Thus to get the same effect as:

L2 = [] for i in range(3):L2.append(L1[i])

it is much shorter and far faster to use

L2 = list(L1[:3]) # "list" is redundant if L1 is a list.

Note that the functionally-oriented built-in functions such as?map(),?zip(), and friends can be a convenient accelerator for loops that perform a single task. For example to pair the elements of two lists together:

>>> >>> zip([1, 2, 3], [4, 5, 6]) [(1, 4), (2, 5), (3, 6)]

or to compute a number of sines:

>>> >>> map(math.sin, (1, 2, 3, 4)) [0.841470984808, 0.909297426826, 0.14112000806, -0.756802495308]

The operation completes very quickly in such cases.

Other examples include the?join()?and?split()?methods of string objects. For example if s1..s7 are large (10K+) strings then"".join([s1,s2,s3,s4,s5,s6,s7])?may be far faster than the more obvious?s1+s2+s3+s4+s5+s6+s7, since the “summation” will compute many subexpressions, whereas?join()?does all the copying in one pass. For manipulating strings, use the?replace()?and the?format()?methods on string objects. Use regular expressions only when you’re not dealing with constant string patterns. You may still use?the old % operations?string?%?tuple?and?string?%?dictionary.

Be sure to use the?list.sort()?built-in method to do sorting, and see the?sorting mini-HOWTO?for examples of moderately advanced usage.list.sort()?beats other techniques for sorting in all but the most extreme circumstances.

Another common trick is to “push loops into functions or methods.” For example suppose you have a program that runs slowly and you use the profiler to determine that a Python function?ff()?is being called lots of times. If you notice that?ff():

def ff(x):... # do something with x computing result...return result

tends to be called in loops like:

list = map(ff, oldlist)

or:

for x in sequence:value = ff(x)... # do something with value...

then you can often eliminate function call overhead by rewriting?ff()?to:

def ffseq(seq):resultseq = []for x in seq:... # do something with x computing result...resultseq.append(result)return resultseq

and rewrite the two examples to?list?=?ffseq(oldlist)?and to:

for value in ffseq(sequence):... # do something with value...

Single calls to?ff(x)?translate to?ffseq([x])[0]?with little penalty. Of course this technique is not always appropriate and there are other variants which you can figure out.

You can gain some performance by explicitly storing the results of a function or method lookup into a local variable. A loop like:

for key in token:dict[key] = dict.get(key, 0) + 1

resolves?dict.get?every iteration. If the method isn’t going to change, a slightly faster implementation is:

dict_get = dict.get # look up the method once for key in token:dict[key] = dict_get(key, 0) + 1

Default arguments can be used to determine values once, at compile time instead of at run time. This can only be done for functions or objects which will not be changed during program execution, such as replacing

def degree_sin(deg):return math.sin(deg * math.pi / 180.0)

with

def degree_sin(deg, factor=math.pi/180.0, sin=math.sin):return sin(deg * factor)

Because this trick uses default arguments for terms which should not be changed, it should only be used when you are not concerned with presenting a possibly confusing API to your users.

Core Language

Why am I getting an UnboundLocalError when the variable has a value?

It can be a surprise to get the UnboundLocalError in previously working code when it is modified by adding an assignment statement somewhere in the body of a function.

This code:

>>> >>> x = 10 >>> def bar(): ... print x >>> bar() 10

works, but this code:

>>> >>> x = 10 >>> def foo(): ... print x ... x += 1

results in an UnboundLocalError:

>>> >>> foo() Traceback (most recent call last):... UnboundLocalError: local variable 'x' referenced before assignment

This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to?x, the compiler recognizes it as a local variable. Consequently when the earlier?print?x?attempts to print the uninitialized local variable and an error results.

In the example above you can access the outer scope variable by declaring it global:

>>> >>> x = 10 >>> def foobar(): ... global x ... print x ... x += 1 >>> foobar() 10

This explicit declaration is required in order to remind you that (unlike the superficially analogous situation with class and instance variables) you are actually modifying the value of the variable in the outer scope:

>>> >>> print x 11

What are the rules for local and global variables in Python?

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring?global?for assigned variables provides a bar against unintended side-effects. On the other hand, if?global?was required for all global references, you’d be using?global?all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the?global?declaration for identifying side-effects.

Why do lambdas defined in a loop with different values all return the same result?

Assume you use a for loop to define a few different lambdas (or even plain functions), e.g.:

>>> >>> squares = [] >>> for x in range(5): ... squares.append(lambda: x**2)

This gives you a list that contains 5 lambdas that calculate?x**2. You might expect that, when called, they would return, respectively,0,?1,?4,?9, and?16. However, when you actually try you will see that they all return?16:

>>> >>> squares[2]() 16 >>> squares[4]() 16

This happens because?x?is not local to the lambdas, but is defined in the outer scope, and it is accessed when the lambda is called — not when it is defined. At the end of the loop, the value of?x?is?4, so all the functions now return?4**2, i.e.?16. You can also verify this by changing the value of?x?and see how the results of the lambdas change:

>>> >>> x = 8 >>> squares[2]() 64

In order to avoid this, you need to save the values in variables local to the lambdas, so that they don’t rely on the value of the global?x:

>>> >>> squares = [] >>> for x in range(5): ... squares.append(lambda n=x: n**2)

Here,?n=x?creates a new variable?n?local to the lambda and computed when the lambda is defined so that it has the same value that?x?had at that point in the loop. This means that the value of?n?will be?0?in the first lambda,?1?in the second,?2?in the third, and so on. Therefore each lambda will now return the correct result:

>>> >>> squares[2]() 4 >>> squares[4]() 16

Note that this behaviour is not peculiar to lambdas, but applies to regular functions too.

How do I share global variables across modules?

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example:

config.py:

x = 0 # Default value of the 'x' configuration setting

mod.py:

import config config.x = 1

main.py:

import config import mod print config.x

Note that using a module is also the basis for implementing the Singleton design pattern, for the same reason.

What are the “best practices” for using import in a module?

In general, don’t use?from?modulename?import?*. Doing so clutters the importer’s namespace, and makes it much harder for linters to detect undefined names.

Import modules at the top of a file. Doing so makes it clear what other modules your code requires and avoids questions of whether the module name is in scope. Using one import per line makes it easy to add and delete module imports, but using multiple imports per line uses less screen space.

It’s good practice if you import modules in the following order:

  • standard library modules – e.g.?sys,?os,?getopt,?re
  • third-party library modules (anything installed in Python’s site-packages directory) – e.g. mx.DateTime, ZODB, PIL.Image, etc.
  • locally-developed modules
  • Only use explicit relative package imports. If you’re writing code that’s in the?package.sub.m1?module and want to import?package.sub.m2, do not just write?import?m2, even though it’s legal. Write?from?package.sub?import?m2?or?from?.?import?m2?instead.

    It is sometimes necessary to move imports to a function or class to avoid problems with circular imports. Gordon McMillan says:

    Circular imports are fine where both modules use the “import <module>” form of import. They fail when the 2nd module wants to grab a name out of the first (“from module import name”) and the import is at the top level. That’s because names in the 1st are not yet available, because the first module is busy importing the 2nd.

    In this case, if the second module is only used in one function, then the import can easily be moved into that function. By the time the import is called, the first module will have finished initializing, and the second module can do its import.

    It may also be necessary to move imports out of the top level of code if some of the modules are platform-specific. In that case, it may not even be possible to import all of the modules at the top of the file. In this case, importing the correct modules in the corresponding platform-specific code is a good option.

    Only move imports into a local scope, such as inside a function definition, if it’s necessary to solve a problem such as avoiding a circular import or are trying to reduce the initialization time of a module. This technique is especially helpful if many of the imports are unnecessary depending on how the program executes. You may also want to move imports into a function if the modules are only ever used in that function. Note that loading a module the first time may be expensive because of the one time initialization of the module, but loading a module multiple times is virtually free, costing only a couple of dictionary lookups. Even if the module name has gone out of scope, the module is probably available in?sys.modules.

    Why are default values shared between objects?

    This type of bug commonly bites neophyte programmers. Consider this function:

    def foo(mydict={}): # Danger: shared reference to one dict for all calls... compute something ...mydict[key] = valuereturn mydict

    The first time you call this function,?mydict?contains a single item. The second time,?mydict?contains two items because when?foo()?begins executing,?mydict?starts out with an item already in it.

    It is often expected that a function call creates new objects for default values. This is not what happens. Default values are created exactly once, when the function is defined. If that object is changed, like the dictionary in this example, subsequent calls to the function will refer to this changed object.

    By definition, immutable objects such as numbers, strings, tuples, and?None, are safe from change. Changes to mutable objects such as dictionaries, lists, and class instances can lead to confusion.

    Because of this feature, it is good programming practice to not use mutable objects as default values. Instead, use?None?as the default value and inside the function, check if the parameter is?None?and create a new list/dictionary/whatever if it is. For example, don’t write:

    def foo(mydict={}):...

    but:

    def foo(mydict=None):if mydict is None:mydict = {} # create a new dict for local namespace

    This feature can be useful. When you have a function that’s time-consuming to compute, a common technique is to cache the parameters and the resulting value of each call to the function, and return the cached value if the same value is requested again. This is called “memoizing”, and can be implemented like this:

    # Callers will never provide a third parameter for this function. def expensive(arg1, arg2, _cache={}):if (arg1, arg2) in _cache:return _cache[(arg1, arg2)]# Calculate the valueresult = ... expensive computation ..._cache[(arg1, arg2)] = result # Store result in the cachereturn result

    You could use a global variable containing a dictionary instead of the default value; it’s a matter of taste.

    How can I pass optional or keyword parameters from one function to another?

    Collect the arguments using the?*?and?**?specifiers in the function’s parameter list; this gives you the positional arguments as a tuple and the keyword arguments as a dictionary. You can then pass these arguments when calling another function by using?*?and?**:

    def f(x, *args, **kwargs):...kwargs['width'] = '14.3c'...g(x, *args, **kwargs)

    In the unlikely case that you care about Python versions older than 2.0, use?apply():

    def f(x, *args, **kwargs):...kwargs['width'] = '14.3c'...apply(g, (x,)+args, kwargs)

    What is the difference between arguments and parameters?

    Parameters?are defined by the names that appear in a function definition, whereas?arguments?are the values actually passed to a function when calling it. Parameters define what types of arguments a function can accept. For example, given the function definition:

    def func(foo, bar=None, **kwargs):pass

    foo,?bar?and?kwargs?are parameters of?func. However, when calling?func, for example:

    func(42, bar=314, extra=somevar)

    the values?42,?314, and?somevar?are arguments.

    Why did changing list ‘y’ also change list ‘x’?

    If you wrote code like:

    >>> >>> x = [] >>> y = x >>> y.append(10) >>> y [10] >>> x [10]

    you might be wondering why appending an element to?y?changed?x?too.

    There are two factors that produce this result:

  • Variables are simply names that refer to objects. Doing?y?=?x?doesn’t create a copy of the list – it creates a new variable?y?that refers to the same object?x?refers to. This means that there is only one object (the list), and both?x?and?y?refer to it.
  • Lists are?mutable, which means that you can change their content.
  • After the call to?append(), the content of the mutable object has changed from?[]?to?[10]. Since both the variables refer to the same object, using either name accesses the modified value?[10].

    If we instead assign an immutable object to?x:

    >>> >>> x = 5 # ints are immutable >>> y = x >>> x = x + 1 # 5 can't be mutated, we are creating a new object here >>> x 6 >>> y 5

    we can see that in this case?x?and?y?are not equal anymore. This is because integers are?immutable, and when we do?x?=?x?+?1?we are not mutating the int?5?by incrementing its value; instead, we are creating a new object (the int?6) and assigning it to?x?(that is, changing which object?x?refers to). After this assignment we have two objects (the ints?6?and?5) and two variables that refer to them (x?now refers to?6?but?y?still refers to?5).

    Some operations (for example?y.append(10)?and?y.sort()) mutate the object, whereas superficially similar operations (for example?y?=?y?+?[10]and?sorted(y)) create a new object. In general in Python (and in all cases in the standard library) a method that mutates an object will return?None?to help avoid getting the two types of operations confused. So if you mistakenly write?y.sort()?thinking it will give you a sorted copy of?y, you’ll instead end up with?None, which will likely cause your program to generate an easily diagnosed error.

    However, there is one class of operations where the same operation sometimes has different behaviors with different types: the augmented assignment operators. For example,?+=?mutates lists but not tuples or ints (a_list?+=?[1,?2,?3]?is equivalent to?a_list.extend([1,?2,?3])?and mutates?a_list, whereas?some_tuple?+=?(1,?2,?3)?and?some_int?+=?1?create new objects).

    In other words:

    • If we have a mutable object (list,?dict,?set, etc.), we can use some specific operations to mutate it and all the variables that refer to it will see the change.
    • If we have an immutable object (str,?int,?tuple, etc.), all the variables that refer to it will always see the same value, but operations that transform that value into a new value always return a new object.

    If you want to know if two variables refer to the same object or not, you can use the?is?operator, or the built-in function?id().

    How do I write a function with output parameters (call by reference)?

    Remember that arguments are passed by assignment in Python. Since assignment just creates references to objects, there’s no alias between an argument name in the caller and callee, and so no call-by-reference per se. You can achieve the desired effect in a number of ways.

  • By returning a tuple of the results:

    def func2(a, b):a = 'new-value' # a and b are local namesb = b + 1 # assigned to new objectsreturn a, b # return new valuesx, y = 'old-value', 99 x, y = func2(x, y) print x, y # output: new-value 100

    This is almost always the clearest solution.

  • By using global variables. This isn’t thread-safe, and is not recommended.

  • By passing a mutable (changeable in-place) object:

    def func1(a):a[0] = 'new-value' # 'a' references a mutable lista[1] = a[1] + 1 # changes a shared objectargs = ['old-value', 99] func1(args) print args[0], args[1] # output: new-value 100
  • By passing in a dictionary that gets mutated:

    def func3(args):args['a'] = 'new-value' # args is a mutable dictionaryargs['b'] = args['b'] + 1 # change it in-placeargs = {'a': 'old-value', 'b': 99} func3(args) print args['a'], args['b']
  • Or bundle up values in a class instance:

    class callByRef:def __init__(self, **args):for (key, value) in args.items():setattr(self, key, value)def func4(args):args.a = 'new-value' # args is a mutable callByRefargs.b = args.b + 1 # change object in-placeargs = callByRef(a='old-value', b=99) func4(args) print args.a, args.b

    There’s almost never a good reason to get this complicated.

  • Your best choice is to return a tuple containing the multiple results.

    How do you make a higher order function in Python?

    You have two choices: you can use nested scopes or you can use callable objects. For example, suppose you wanted to define?linear(a,b)which returns a function?f(x)?that computes the value?a*x+b. Using nested scopes:

    def linear(a, b):def result(x):return a * x + breturn result

    Or using a callable object:

    class linear:def __init__(self, a, b):self.a, self.b = a, bdef __call__(self, x):return self.a * x + self.b

    In both cases,

    taxes = linear(0.3, 2)

    gives a callable object where?taxes(10e6)?==?0.3?*?10e6?+?2.

    The callable object approach has the disadvantage that it is a bit slower and results in slightly longer code. However, note that a collection of callables can share their signature via inheritance:

    class exponential(linear):# __init__ inheriteddef __call__(self, x):return self.a * (x ** self.b)

    Object can encapsulate state for several methods:

    class counter:value = 0def set(self, x):self.value = xdef up(self):self.value = self.value + 1def down(self):self.value = self.value - 1count = counter() inc, dec, reset = count.up, count.down, count.set

    Here?inc(),?dec()?and?reset()?act like functions which share the same counting variable.

    How do I copy an object in Python?

    In general, try?copy.copy()?or?copy.deepcopy()?for the general case. Not all objects can be copied, but most can.

    Some objects can be copied more easily. Dictionaries have a?copy()?method:

    newdict = olddict.copy()

    Sequences can be copied by slicing:

    new_l = l[:]

    How can I find the methods or attributes of an object?

    For an instance x of a user-defined class,?dir(x)?returns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class.

    How can my code discover the name of an object?

    Generally speaking, it can’t, because objects don’t really have names. Essentially, assignment always binds a name to a value; The same is true of?def?and?class?statements, but in that case the value is a callable. Consider the following code:

    >>> >>> class A: ... pass ... >>> B = A >>> a = B() >>> b = a >>> print b <__main__.A instance at 0x16D07CC> >>> print a <__main__.A instance at 0x16D07CC>

    Arguably the class has a name: even though it is bound to two names and invoked through the name B the created instance is still reported as an instance of class A. However, it is impossible to say whether the instance’s name is a or b, since both names are bound to the same value.

    Generally speaking it should not be necessary for your code to “know the names” of particular values. Unless you are deliberately writing introspective programs, this is usually an indication that a change of approach might be beneficial.

    In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to this question:

    The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn’t really care – so the only way to find out what it’s called is to ask all your neighbours (namespaces) if it’s their cat (object)...

    ....and don’t be surprised if you’ll find that it’s known by many names, or no name at all!

    What’s up with the comma operator’s precedence?

    Comma is not an operator in Python. Consider this session:

    >>> >>> "a" in "b", "a" (False, 'a')

    Since the comma is not an operator, but a separator between expressions the above is evaluated as if you had entered:

    ("a" in "b"), "a"

    not:

    "a" in ("b", "a")

    The same is true of the various assignment operators (=,?+=?etc). They are not truly operators but syntactic delimiters in assignment statements.

    Is there an equivalent of C’s ”?:” ternary operator?

    Yes, this feature was added in Python 2.5. The syntax would be as follows:

    [on_true] if [expression] else [on_false]x, y = 50, 25small = x if x < y else y

    For versions previous to 2.5 the answer would be ‘No’.

    Is it possible to write obfuscated one-liners in Python?

    Yes. Usually this is done by nesting?lambda?within?lambda. See the following three examples, due to Ulf Bartelt:

    # Primes < 1000 print filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0, map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))# First 10 Fibonacci numbers print map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1: f(x,f), range(10))# Mandelbrot set print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y, Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM, Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro, i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y >=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr( 64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24) # \___ ___/ \___ ___/ | | |__ lines on screen # V V | |______ columns on screen # | | |__________ maximum of "iterations" # | |_________________ range on y axis # |____________________________ range on x axis

    Don’t try this at home, kids!

    Numbers and strings

    How do I specify hexadecimal and octal integers?

    To specify an octal digit, precede the octal value with a zero, and then a lower or uppercase “o”. For example, to set the variable “a” to the octal value “10” (8 in decimal), type:

    >>> >>> a = 0o10 >>> a 8

    Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero, and then a lower or uppercase “x”. Hexadecimal digits can be specified in lower or uppercase. For example, in the Python interpreter:

    >>> >>> a = 0xa5 >>> a 165 >>> b = 0XB2 >>> b 178

    Why does -22 // 10 return -3?

    It’s primarily driven by the desire that?i?%?j?have the same sign as?j. If you want that, and also want:

    i == (i // j) * j + (i % j)

    then integer division has to return the floor. C also requires that identity to hold, and then compilers that truncate?i?//?j?need to make?i?%?j?have the same sign as?i.

    There are few real use cases for?i?%?j?when?j?is negative. When?j?is positive, there are many, and in virtually all of them it’s more useful for?i?%?j?to be?>=?0. If the clock says 10 now, what did it say 200 hours ago??-190?%?12?==?2?is useful;?-190?%?12?==?-10?is a bug waiting to bite.

    Note

    ?

    On Python 2,?a?/?b?returns the same as?a?//?b?if?__future__.division?is not in effect. This is also known as “classic” division.

    How do I convert a string to a number?

    For integers, use the built-in?int()?type constructor, e.g.?int('144')?==?144. Similarly,?float()?converts to floating-point, e.g.?float('144')==?144.0.

    By default, these interpret the number as decimal, so that?int('0144')?==?144?and?int('0x144')?raises?ValueError.?int(string,?base)?takes the base to convert from as a second optional argument, so?int('0x144',?16)?==?324. If the base is specified as 0, the number is interpreted using Python’s rules: a leading ‘0’ indicates octal, and ‘0x’ indicates a hex number.

    Do not use the built-in function?eval()?if all you need is to convert strings to numbers.?eval()?will be significantly slower and it presents a security risk: someone could pass you a Python expression that might have unwanted side effects. For example, someone could pass?__import__('os').system("rm?-rf?$HOME")?which would erase your home directory.

    eval()?also has the effect of interpreting numbers as Python expressions, so that e.g.?eval('09')?gives a syntax error because Python regards numbers starting with ‘0’ as octal (base 8).

    How do I convert a number to a string?

    To convert, e.g., the number 144 to the string ‘144’, use the built-in type constructor?str(). If you want a hexadecimal or octal representation, use the built-in functions?hex()?or?oct(). For fancy formatting, see the?Format String Syntax?section, e.g.?"{:04d}".format(144)?yields?'0144'?and?"{:.3f}".format(1/3)?yields?'0.333'. You may also use?the % operator?on strings. See the library reference manual for details.

    How do I modify a string in place?

    You can’t, because strings are immutable. If you need an object with this ability, try converting the string to a list or use the array module:

    >>> >>> import io >>> s = "Hello, world" >>> a = list(s) >>> print a ['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd'] >>> a[7:] = list("there!") >>> ''.join(a) 'Hello, there!'>>> import array >>> a = array.array('c', s) >>> print a array('c', 'Hello, world') >>> a[0] = 'y'; print a array('c', 'yello, world') >>> a.tostring() 'yello, world'

    How do I use strings to call functions/methods?

    There are various techniques.

    • The best is to use a dictionary that maps strings to functions. The primary advantage of this technique is that the strings do not need to match the names of the functions. This is also the primary technique used to emulate a case construct:

      def a():passdef b():passdispatch = {'go': a, 'stop': b} # Note lack of parens for funcsdispatch[get_input()]() # Note trailing parens to call function
    • Use the built-in function?getattr():

      import foo getattr(foo, 'bar')()

      Note that?getattr()?works on any object, including classes, class instances, modules, and so on.

      This is used in several places in the standard library, like this:

      class Foo:def do_foo(self):...def do_bar(self):...f = getattr(foo_instance, 'do_' + opname) f()
    • Use?locals()?or?eval()?to resolve the function name:

      def myFunc():print "hello"fname = "myFunc"f = locals()[fname] f()f = eval(fname) f()

      Note: Using?eval()?is slow and dangerous. If you don’t have absolute control over the contents of the string, someone could pass a string that resulted in an arbitrary function being executed.

    Is there an equivalent to Perl’s chomp() for removing trailing newlines from strings?

    Starting with Python 2.2, you can use?S.rstrip("\r\n")?to remove all occurrences of any line terminator from the end of the string?Swithout removing other trailing whitespace. If the string?S?represents more than one line, with several empty lines at the end, the line terminators for all the blank lines will be removed:

    >>> >>> lines = ("line 1 \r\n" ... "\r\n" ... "\r\n") >>> lines.rstrip("\n\r") 'line 1 '

    Since this is typically only desired when reading text one line at a time, using?S.rstrip()?this way works well.

    For older versions of Python, there are two partial substitutes:

    • If you want to remove all trailing whitespace, use the?rstrip()?method of string objects. This removes all trailing whitespace, not just a single newline.
    • Otherwise, if there is only one line in the string?S, use?S.splitlines()[0].

    Is there a scanf() or sscanf() equivalent?

    Not as such.

    For simple input parsing, the easiest approach is usually to split the line into whitespace-delimited words using the?split()?method of string objects and then convert decimal strings to numeric values using?int()?or?float().?split()?supports an optional “sep” parameter which is useful if the line uses something other than whitespace as a separator.

    For more complicated input parsing, regular expressions are more powerful than C’s?sscanf()?and better suited for the task.

    What does ‘UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)’ mean?

    This error indicates that your Python installation can handle only 7-bit ASCII strings. There are a couple ways to fix or work around the problem.

    If your programs must handle data in arbitrary character set encodings, the environment the application runs in will generally identify the encoding of the data it is handing you. You need to convert the input to Unicode data using that encoding. For example, a program that handles email or web input will typically find character set encoding information in Content-Type headers. This can then be used to properly convert input data to Unicode. Assuming the string referred to by?value?is encoded as UTF-8:

    value = unicode(value, "utf-8")

    will return a Unicode object. If the data is not correctly encoded as UTF-8, the above call will raise a?UnicodeError?exception.

    If you only want strings converted to Unicode which have non-ASCII data, you can try converting them first assuming an ASCII encoding, and then generate Unicode objects if that fails:

    try:x = unicode(value, "ascii") except UnicodeError:value = unicode(value, "utf-8") else:# value was valid ASCII datapass

    It’s possible to set a default encoding in a file called?sitecustomize.py?that’s part of the Python library. However, this isn’t recommended because changing the Python-wide default encoding may cause third-party extension modules to fail.

    Note that on Windows, there is an encoding known as “mbcs”, which uses an encoding specific to your current locale. In many cases, and particularly when working with COM, this may be an appropriate default encoding to use.

    Sequences (Tuples/Lists)

    How do I convert between tuples and lists?

    The type constructor?tuple(seq)?converts any sequence (actually, any iterable) into a tuple with the same items in the same order.

    For example,?tuple([1,?2,?3])?yields?(1,?2,?3)?and?tuple('abc')?yields?('a',?'b',?'c'). If the argument is a tuple, it does not make a copy but returns the same object, so it is cheap to call?tuple()?when you aren’t sure that an object is already a tuple.

    The type constructor?list(seq)?converts any sequence or iterable into a list with the same items in the same order. For example,?list((1,?2,3))?yields?[1,?2,?3]?and?list('abc')?yields?['a',?'b',?'c']. If the argument is a list, it makes a copy just like?seq[:]?would.

    What’s a negative index?

    Python sequences are indexed with positive numbers and negative numbers. For positive numbers 0 is the first index 1 is the second index and so forth. For negative indices -1 is the last index and -2 is the penultimate (next to last) index and so forth. Think of?seq[-n]?as the same as?seq[len(seq)-n].

    Using negative indices can be very convenient. For example?S[:-1]?is all of the string except for its last character, which is useful for removing the trailing newline from a string.

    How do I iterate over a sequence in reverse order?

    Use the?reversed()?built-in function, which is new in Python 2.4:

    for x in reversed(sequence):... # do something with x ...

    This won’t touch your original sequence, but build a new copy with reversed order to iterate over.

    With Python 2.3, you can use an extended slice syntax:

    for x in sequence[::-1]:... # do something with x ...

    How do you remove duplicates from a list?

    See the Python Cookbook for a long discussion of many ways to do this:

    https://code.activestate.com/recipes/52560/

    If you don’t mind reordering the list, sort it and then scan from the end of the list, deleting duplicates as you go:

    if mylist:mylist.sort()last = mylist[-1]for i in range(len(mylist)-2, -1, -1):if last == mylist[i]:del mylist[i]else:last = mylist[i]

    If all elements of the list may be used as dictionary keys (i.e. they are all hashable) this is often faster

    d = {} for x in mylist:d[x] = 1 mylist = list(d.keys())

    In Python 2.5 and later, the following is possible instead:

    mylist = list(set(mylist))

    This converts the list into a set, thereby removing duplicates, and then back into a list.

    How do you make an array in Python?

    Use a list:

    ["this", 1, "is", "an", "array"]

    Lists are equivalent to C or Pascal arrays in their time complexity; the primary difference is that a Python list can contain objects of many different types.

    The?array?module also provides methods for creating arrays of fixed types with compact representations, but they are slower to index than lists. Also note that the Numeric extensions and others define array-like structures with various characteristics as well.

    To get Lisp-style linked lists, you can emulate cons cells using tuples:

    lisp_list = ("like", ("this", ("example", None) ) )

    If mutability is desired, you could use lists instead of tuples. Here the analogue of lisp car is?lisp_list[0]?and the analogue of cdr islisp_list[1]. Only do this if you’re sure you really need to, because it’s usually a lot slower than using Python lists.

    How do I create a multidimensional list?

    You probably tried to make a multidimensional array like this:

    >>> >>> A = [[None] * 2] * 3

    This looks correct if you print it:

    >>> >>> A [[None, None], [None, None], [None, None]]

    But when you assign a value, it shows up in multiple places:

    >>> >>> A[0][0] = 5 >>> A [[5, None], [5, None], [5, None]]

    The reason is that replicating a list with?*?doesn’t create copies, it only creates references to the existing objects. The?*3?creates a list containing 3 references to the same list of length two. Changes to one row will show in all rows, which is almost certainly not what you want.

    The suggested approach is to create a list of the desired length first and then fill in each element with a newly created list:

    A = [None] * 3 for i in range(3):A[i] = [None] * 2

    This generates a list containing 3 different lists of length two. You can also use a list comprehension:

    w, h = 2, 3 A = [[None] * w for i in range(h)]

    Or, you can use an extension that provides a matrix datatype;?Numeric Python?is the best known.

    How do I apply a method to a sequence of objects?

    Use a list comprehension:

    result = [obj.method() for obj in mylist]

    More generically, you can try the following function:

    def method_map(objects, method, arguments):"""method_map([a,b], "meth", (1,2)) gives [a.meth(1,2), b.meth(1,2)]"""nobjects = len(objects)methods = map(getattr, objects, [method]*nobjects)return map(apply, methods, [arguments]*nobjects)

    Why does a_tuple[i] += [‘item’] raise an exception when the addition works?

    This is because of a combination of the fact that augmented assignment operators are?assignment?operators, and the difference between mutable and immutable objects in Python.

    This discussion applies in general when augmented assignment operators are applied to elements of a tuple that point to mutable objects, but we’ll use a?list?and?+=?as our exemplar.

    If you wrote:

    >>> >>> a_tuple = (1, 2) >>> a_tuple[0] += 1 Traceback (most recent call last):... TypeError: 'tuple' object does not support item assignment

    The reason for the exception should be immediately clear:?1?is added to the object?a_tuple[0]?points to (1), producing the result object,2, but when we attempt to assign the result of the computation,?2, to element?0?of the tuple, we get an error because we can’t change what an element of a tuple points to.

    Under the covers, what this augmented assignment statement is doing is approximately this:

    >>> >>> result = a_tuple[0] + 1 >>> a_tuple[0] = result Traceback (most recent call last):... TypeError: 'tuple' object does not support item assignment

    It is the assignment part of the operation that produces the error, since a tuple is immutable.

    When you write something like:

    >>> >>> a_tuple = (['foo'], 'bar') >>> a_tuple[0] += ['item'] Traceback (most recent call last):... TypeError: 'tuple' object does not support item assignment

    The exception is a bit more surprising, and even more surprising is the fact that even though there was an error, the append worked:

    >>> >>> a_tuple[0] ['foo', 'item']

    To see why this happens, you need to know that (a) if an object implements an?__iadd__?magic method, it gets called when the?+=?augmented assignment is executed, and its return value is what gets used in the assignment statement; and (b) for lists,?__iadd__?is equivalent to calling?extend?on the list and returning the list. That’s why we say that for lists,?+=?is a “shorthand” for?list.extend:

    >>> >>> a_list = [] >>> a_list += [1] >>> a_list [1]

    This is equivalent to:

    >>> >>> result = a_list.__iadd__([1]) >>> a_list = result

    The object pointed to by a_list has been mutated, and the pointer to the mutated object is assigned back to?a_list. The end result of the assignment is a no-op, since it is a pointer to the same object that?a_list?was previously pointing to, but the assignment still happens.

    Thus, in our tuple example what is happening is equivalent to:

    >>> >>> result = a_tuple[0].__iadd__(['item']) >>> a_tuple[0] = result Traceback (most recent call last):... TypeError: 'tuple' object does not support item assignment

    The?__iadd__?succeeds, and thus the list is extended, but even though?result?points to the same object that?a_tuple[0]?already points to, that final assignment still results in an error, because tuples are immutable.

    Dictionaries

    How can I get a dictionary to display its keys in a consistent order?

    You can’t. Dictionaries store their keys in an unpredictable order, so the display order of a dictionary’s elements will be similarly unpredictable.

    This can be frustrating if you want to save a printable version to a file, make some changes and then compare it with some other printed dictionary. In this case, use the?pprint?module to pretty-print the dictionary; the items will be presented in order sorted by the key.

    A more complicated solution is to subclass?dict?to create a?SortedDict?class that prints itself in a predictable order. Here’s one simpleminded implementation of such a class:

    class SortedDict(dict):def __repr__(self):keys = sorted(self.keys())result = ("{!r}: {!r}".format(k, self[k]) for k in keys)return "{{{}}}".format(", ".join(result))__str__ = __repr__

    This will work for many common situations you might encounter, though it’s far from a perfect solution. The largest flaw is that if some values in the dictionary are also dictionaries, their values won’t be presented in any particular order.

    I want to do a complicated sort: can you do a Schwartzian Transform in Python?

    The technique, attributed to Randal Schwartz of the Perl community, sorts the elements of a list by a metric which maps each element to its “sort value”. In Python, just use the?key?argument for the?sort()?method:

    Isorted = L[:] Isorted.sort(key=lambda s: int(s[10:15]))

    The?key?argument is new in Python 2.4, for older versions this kind of sorting is quite simple to do with list comprehensions. To sort a list of strings by their uppercase values:

    tmp1 = [(x.upper(), x) for x in L] # Schwartzian transform tmp1.sort() Usorted = [x[1] for x in tmp1]

    To sort by the integer value of a subfield extending from positions 10-15 in each string:

    tmp2 = [(int(s[10:15]), s) for s in L] # Schwartzian transform tmp2.sort() Isorted = [x[1] for x in tmp2]

    Note that Isorted may also be computed by

    def intfield(s):return int(s[10:15])def Icmp(s1, s2):return cmp(intfield(s1), intfield(s2))Isorted = L[:] Isorted.sort(Icmp)

    but since this method calls?intfield()?many times for each element of L, it is slower than the Schwartzian Transform.

    How can I sort one list by values from another list?

    Merge them into a single list of tuples, sort the resulting list, and then pick out the element you want.

    >>> >>> list1 = ["what", "I'm", "sorting", "by"] >>> list2 = ["something", "else", "to", "sort"] >>> pairs = zip(list1, list2) >>> pairs [('what', 'something'), ("I'm", 'else'), ('sorting', 'to'), ('by', 'sort')] >>> pairs.sort() >>> result = [ x[1] for x in pairs ] >>> result ['else', 'sort', 'to', 'something']

    An alternative for the last step is:

    >>> >>> result = [] >>> for p in pairs: result.append(p[1])

    If you find this more legible, you might prefer to use this instead of the final list comprehension. However, it is almost twice as slow for long lists. Why? First, the?append()?operation has to reallocate memory, and while it uses some tricks to avoid doing that each time, it still has to do it occasionally, and that costs quite a bit. Second, the expression “result.append” requires an extra attribute lookup, and third, there’s a speed reduction from having to make all those function calls.

    Objects

    What is a class?

    A class is the particular object type created by executing a class statement. Class objects are used as templates to create instance objects, which embody both the data (attributes) and code (methods) specific to a datatype.

    A class can be based on one or more other classes, called its base class(es). It then inherits the attributes and methods of its base classes. This allows an object model to be successively refined by inheritance. You might have a generic?Mailbox?class that provides basic accessor methods for a mailbox, and subclasses such as?MboxMailbox,?MaildirMailbox,?OutlookMailbox?that handle various specific mailbox formats.

    What is a method?

    A method is a function on some object?x?that you normally call as?x.name(arguments...). Methods are defined as functions inside the class definition:

    class C:def meth(self, arg):return arg * 2 + self.attribute

    What is self?

    Self is merely a conventional name for the first argument of a method. A method defined as?meth(self,?a,?b,?c)?should be called as?x.meth(a,?b,c)?for some instance?x?of the class in which the definition occurs; the called method will think it is called as?meth(x,?a,?b,?c).

    See also?Why must ‘self’ be used explicitly in method definitions and calls?.

    How do I check if an object is an instance of a given class or of a subclass of it?

    Use the built-in function?isinstance(obj,?cls). You can check if an object is an instance of any of a number of classes by providing a tuple instead of a single class, e.g.?isinstance(obj,?(class1,?class2,?...)), and can also check whether an object is one of Python’s built-in types, e.g.?isinstance(obj,?str)?or?isinstance(obj,?(int,?long,?float,?complex)).

    Note that most programs do not use?isinstance()?on user-defined classes very often. If you are developing the classes yourself, a more proper object-oriented style is to define methods on the classes that encapsulate a particular behaviour, instead of checking the object’s class and doing a different thing based on what class it is. For example, if you have a function that does something:

    def search(obj):if isinstance(obj, Mailbox):... # code to search a mailboxelif isinstance(obj, Document):... # code to search a documentelif ...

    A better approach is to define a?search()?method on all the classes and just call it:

    class Mailbox:def search(self):... # code to search a mailboxclass Document:def search(self):... # code to search a documentobj.search()

    What is delegation?

    Delegation is an object oriented technique (also called a design pattern). Let’s say you have an object?x?and want to change the behaviour of just one of its methods. You can create a new class that provides a new implementation of the method you’re interested in changing and delegates all other methods to the corresponding method of?x.

    Python programmers can easily implement delegation. For example, the following class implements a class that behaves like a file but converts all written data to uppercase:

    class UpperOut:def __init__(self, outfile):self._outfile = outfiledef write(self, s):self._outfile.write(s.upper())def __getattr__(self, name):return getattr(self._outfile, name)

    Here the?UpperOut?class redefines the?write()?method to convert the argument string to uppercase before calling the underlyingself.__outfile.write()?method. All other methods are delegated to the underlying?self.__outfile?object. The delegation is accomplished via the__getattr__?method; consult?the language reference?for more information about controlling attribute access.

    Note that for more general cases delegation can get trickier. When attributes must be set as well as retrieved, the class must define a__setattr__()?method too, and it must do so carefully. The basic implementation of?__setattr__()?is roughly equivalent to the following:

    class X:...def __setattr__(self, name, value):self.__dict__[name] = value...

    Most?__setattr__()?implementations must modify?self.__dict__?to store local state for self without causing an infinite recursion.

    How do I call a method defined in a base class from a derived class that overrides it?

    If you’re using new-style classes, use the built-in?super()?function:

    class Derived(Base):def meth(self):super(Derived, self).meth()

    If you’re using classic classes: For a class definition such as?class?Derived(Base):?...?you can call method?meth()?defined in?Base?(or one ofBase‘s base classes) as?Base.meth(self,?arguments...). Here,?Base.meth?is an unbound method, so you need to provide the?self?argument.

    How can I organize my code to make it easier to change the base class?

    You could define an alias for the base class, assign the real base class to it before your class definition, and use the alias throughout your class. Then all you have to change is the value assigned to the alias. Incidentally, this trick is also handy if you want to decide dynamically (e.g. depending on availability of resources) which base class to use. Example:

    BaseAlias = <real base class>class Derived(BaseAlias):def meth(self):BaseAlias.meth(self)...

    How do I create static class data and static class methods?

    Both static data and static methods (in the sense of C++ or Java) are supported in Python.

    For static data, simply define a class attribute. To assign a new value to the attribute, you have to explicitly use the class name in the assignment:

    class C:count = 0 # number of times C.__init__ calleddef __init__(self):C.count = C.count + 1def getcount(self):return C.count # or return self.count

    c.count?also refers to?C.count?for any?c?such that?isinstance(c,?C)?holds, unless overridden by?c?itself or by some class on the base-class search path from?c.__class__?back to?C.

    Caution: within a method of C, an assignment like?self.count?=?42?creates a new and unrelated instance named “count” in?self‘s own dict. Rebinding of a class-static data name must always specify the class whether inside a method or not:

    C.count = 314

    Static methods are possible since Python 2.2:

    class C:def static(arg1, arg2, arg3):# No 'self' parameter!...static = staticmethod(static)

    With Python 2.4’s decorators, this can also be written as

    class C:@staticmethoddef static(arg1, arg2, arg3):# No 'self' parameter!...

    However, a far more straightforward way to get the effect of a static method is via a simple module-level function:

    def getcount():return C.count

    If your code is structured so as to define one class (or tightly related class hierarchy) per module, this supplies the desired encapsulation.

    How can I overload constructors (or methods) in Python?

    This answer actually applies to all methods, but the question usually comes up first in the context of constructors.

    In C++ you’d write

    class C {C() { cout << "No arguments\n"; }C(int i) { cout << "Argument is " << i << "\n"; } }

    In Python you have to write a single constructor that catches all cases using default arguments. For example:

    class C:def __init__(self, i=None):if i is None:print "No arguments"else:print "Argument is", i

    This is not entirely equivalent, but close enough in practice.

    You could also try a variable-length argument list, e.g.

    def __init__(self, *args):...

    The same approach works for all method definitions.

    I try to use __spam and I get an error about _SomeClassName__spam.

    Variable names with double leading underscores are “mangled” to provide a simple but effective way to define class private variables. Any identifier of the form?__spam?(at least two leading underscores, at most one trailing underscore) is textually replaced with_classname__spam, where?classname?is the current class name with any leading underscores stripped.

    This doesn’t guarantee privacy: an outside user can still deliberately access the “_classname__spam” attribute, and private values are visible in the object’s?__dict__. Many Python programmers never bother to use private variable names at all.

    My class defines __del__ but it is not called when I delete the object.

    There are several possible reasons for this.

    The del statement does not necessarily call?__del__()?– it simply decrements the object’s reference count, and if this reaches zero__del__()?is called.

    If your data structures contain circular links (e.g. a tree where each child has a parent reference and each parent has a list of children) the reference counts will never go back to zero. Once in a while Python runs an algorithm to detect such cycles, but the garbage collector might run some time after the last reference to your data structure vanishes, so your?__del__()?method may be called at an inconvenient and random time. This is inconvenient if you’re trying to reproduce a problem. Worse, the order in which object’s__del__()?methods are executed is arbitrary. You can run?gc.collect()?to force a collection, but there?are?pathological cases where objects will never be collected.

    Despite the cycle collector, it’s still a good idea to define an explicit?close()?method on objects to be called whenever you’re done with them. The?close()?method can then remove attributes that refer to subobjecs. Don’t call?__del__()?directly –?__del__()?should callclose()?and?close()?should make sure that it can be called more than once for the same object.

    Another way to avoid cyclical references is to use the?weakref?module, which allows you to point to objects without incrementing their reference count. Tree data structures, for instance, should use weak references for their parent and sibling references (if they need them!).

    If the object has ever been a local variable in a function that caught an expression in an except clause, chances are that a reference to the object still exists in that function’s stack frame as contained in the stack trace. Normally, calling?sys.exc_clear()?will take care of this by clearing the last recorded exception.

    Finally, if your?__del__()?method raises an exception, a warning message is printed to?sys.stderr.

    How do I get a list of all instances of a given class?

    Python does not keep track of all instances of a class (or of a built-in type). You can program the class’s constructor to keep track of all instances by keeping a list of weak references to each instance.

    Why does the result of?id()?appear to be not unique?

    The?id()?builtin returns an integer that is guaranteed to be unique during the lifetime of the object. Since in CPython, this is the object’s memory address, it happens frequently that after an object is deleted from memory, the next freshly created object is allocated at the same position in memory. This is illustrated by this example:

    >>> >>> id(1000) 13901272 >>> id(2000) 13901272

    The two ids belong to different integer objects that are created before, and deleted immediately after execution of the?id()?call. To be sure that objects whose id you want to examine are still alive, create another reference to the object:

    >>> >>> a = 1000; b = 2000 >>> id(a) 13901272 >>> id(b) 13891296

    Modules

    How do I create a .pyc file?

    When a module is imported for the first time (or when the source is more recent than the current compiled file) a?.pyc?file containing the compiled code should be created in the same directory as the?.py?file.

    One reason that a?.pyc?file may not be created is permissions problems with the directory. This can happen, for example, if you develop as one user but run as another, such as if you are testing with a web server. Creation of a .pyc file is automatic if you’re importing a module and Python has the ability (permissions, free space, etc...) to write the compiled module back to the directory.

    Running Python on a top level script is not considered an import and no?.pyc?will be created. For example, if you have a top-level modulefoo.py?that imports another module?xyz.py, when you run?foo,?xyz.pyc?will be created since?xyz?is imported, but no?foo.pyc?file will be created since?foo.py?isn’t being imported.

    If you need to create?foo.pyc?– that is, to create a?.pyc?file for a module that is not imported – you can, using the?py_compile?andcompileall?modules.

    The?py_compile?module can manually compile any module. One way is to use the?compile()?function in that module interactively:

    >>> >>> import py_compile >>> py_compile.compile('foo.py')

    This will write the?.pyc?to the same location as?foo.py?(or you can override that with the optional parameter?cfile).

    You can also automatically compile all files in a directory or directories using the?compileall?module. You can do it from the shell prompt by running?compileall.py?and providing the path of a directory containing Python files to compile:

    python -m compileall .

    How do I find the current module name?

    A module can find out its own module name by looking at the predefined global variable?__name__. If this has the value?'__main__', the program is running as a script. Many modules that are usually used by importing them also provide a command-line interface or a self-test, and only execute this code after checking?__name__:

    def main():print 'Running test...'...if __name__ == '__main__':main()

    How can I have modules that mutually import each other?

    Suppose you have the following modules:

    foo.py:

    from bar import bar_var foo_var = 1

    bar.py:

    from foo import foo_var bar_var = 2

    The problem is that the interpreter will perform the following steps:

    • main imports foo
    • Empty globals for foo are created
    • foo is compiled and starts executing
    • foo imports bar
    • Empty globals for bar are created
    • bar is compiled and starts executing
    • bar imports foo (which is a no-op since there already is a module named foo)
    • bar.foo_var = foo.foo_var

    The last step fails, because Python isn’t done with interpreting?foo?yet and the global symbol dictionary for?foo?is still empty.

    The same thing happens when you use?import?foo, and then try to access?foo.foo_var?in global code.

    There are (at least) three possible workarounds for this problem.

    Guido van Rossum recommends avoiding all uses of?from?<module>?import?..., and placing all code inside functions. Initializations of global variables and class variables should use constants or built-in functions only. This means everything from an imported module is referenced as?<module>.<name>.

    Jim Roskind suggests performing steps in the following order in each module:

    • exports (globals, functions, and classes that don’t need imported base classes)
    • import?statements
    • active code (including globals that are initialized from imported values).

    van Rossum doesn’t like this approach much because the imports appear in a strange place, but it does work.

    Matthias Urlichs recommends restructuring your code so that the recursive import is not necessary in the first place.

    These solutions are not mutually exclusive.

    __import__(‘x.y.z’) returns <module ‘x’>; how do I get z?

    Consider using the convenience function?import_module()?from?importlib?instead:

    z = importlib.import_module('x.y.z')

    When I edit an imported module and reimport it, the changes don’t show up. Why does this happen?

    For reasons of efficiency as well as consistency, Python only reads the module file on the first time a module is imported. If it didn’t, in a program consisting of many modules where each one imports the same basic module, the basic module would be parsed and re-parsed many times. To force rereading of a changed module, do this:

    import modname reload(modname)

    Warning: this technique is not 100% fool-proof. In particular, modules containing statements like

    from modname import some_objects

    will continue to work with the old version of the imported objects. If the module contains class definitions, existing class instances will?not?be updated to use the new class definition. This can result in the following paradoxical behaviour:

    >>> >>> import cls >>> c = cls.C() # Create an instance of C >>> reload(cls) <module 'cls' from 'cls.pyc'> >>> isinstance(c, cls.C) # isinstance is false?!? False

    The nature of the problem is made clear if you print out the class objects:

    >>> >>> c.__class__ <class cls.C at 0x7352a0> >>> cls.C <class cls.C at 0x4198d0> from: https://docs.python.org/2/faq/programming.html

    總結

    以上是生活随笔為你收集整理的Python常见问题(2):编程问题 Programming FAQ的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。

    国产精品美女久久久久久免费 | 日韩欧美观看 | av电影一区二区三区 | 久久这里只有精品9 | 国产成人久久av免费高清密臂 | 亚洲另类交 | 亚洲国产小视频在线观看 | 97手机电影网 | 久久国产电影院 | 国产免费人成xvideos视频 | 成人av免费在线看 | 香蕉视频色 | 92国产精品久久久久首页 | 日韩在线观看第一页 | 在线观看视频黄色 | 日韩久久片 | 激情影院在线 | 日韩有码专区 | 精品国产午夜 | 久久av高清 | 免费观看视频黄 | 狠狠色噜噜狠狠狠狠2022 | 黄网站a | 天天做天天爽 | 欧美精品资源 | 婷婷丁香六月天 | av网在线观看 | 首页中文字幕 | 永久av免费在线观看 | 国产亚洲aⅴaaaaaa毛片 | 久久www免费人成看片高清 | 精品资源在线 | 久草免费在线观看 | 奇米影视8888| 中文字幕五区 | 日韩av不卡在线观看 | 一区二区av | 看片黄网站 | 日韩精品一区二区三区外面 | 午夜久久久久久久 | a级国产乱理论片在线观看 伊人宗合网 | 69xx视频 | 久久人人爽人人爽人人片 | 亚洲精品国产精品国自产 | 久久黄色网址 | 久久久私人影院 | 天天草网站 | 欧美污在线观看 | 国产黄视频在线观看 | 天天操综合 | 国产一区二区三区免费在线 | 日韩精品中字 | 久久夜色精品国产欧美一区麻豆 | 亚洲激精日韩激精欧美精品 | www.久久久.com | 久久久久国产视频 | 亚洲美女精品区人人人人 | 精品一区二区6 | 深爱激情丁香 | 亚洲成av人片一区二区梦乃 | 九九热精品视频在线观看 | 97视频在线观看播放 | 国产成人精品一区二区三区在线 | 国产精品久久久一区二区三区网站 | 黄免费在线观看 | 日日夜夜人人天天 | 久久国产精品久久精品 | 国产精品高 | 在线国产片 | 国产精品一区二区三区观看 | www色,com | 久久综合偷偷噜噜噜色 | 国产一级a毛片视频爆浆 | av高清在线观看 | 久久福利影视 | 国产成人精品久久久久蜜臀 | 日韩高清在线一区二区 | 天天射天天做 | 精品国产一区二区三区久久 | 狠狠狠狠狠狠狠干 | 992tv人人网tv亚洲精品 | 18国产精品白浆在线观看免费 | 91在线视频在线 | 成人丁香花 | 国内精品久久久久久久影视麻豆 | 五月天激情婷婷 | 91视频在线免费观看 | 一区二区电影在线观看 | 一区二区三区中文字幕在线 | 中文字幕在线视频一区二区三区 | 日本午夜在线亚洲.国产 | 久久免费视频这里只有精品 | 国产一区二区三区久久久 | 国产 一区二区三区 在线 | 一区二区视频免费在线观看 | 夜夜躁天天躁很躁波 | 色狠狠婷婷 | 狠狠狠色| 亚洲三级视频 | 精品91在线 | 最近中文字幕视频完整版 | 狠狠躁夜夜av | 久久成年人网站 | 亚洲日本成人网 | 精品久久1 | 日韩欧美精品一区二区 | 国产97色在线 | 国产伦精品一区二区三区免费 | 国产成人av | 91大片网站 | 欧美韩日在线 | 久久久久久久国产精品 | 久久美女高清视频 | 欧美日韩一区二区在线观看 | 在线观看国产一区 | 最近乱久中文字幕 | 在线国产日韩 | 精品一区二区综合 | 91成人天堂久久成人 | 丁香高清视频在线看看 | 91免费在线播放 | 免费av在线网站 | 国产亚洲欧美日韩高清 | 99精品国产在热久久下载 | 亚洲精品玖玖玖av在线看 | 成人午夜黄色影院 | 天天躁日日躁狠狠 | 亚洲精品美女在线 | 国内丰满少妇猛烈精品播 | 激情深爱 | 久久精品人人做人人综合老师 | 97视频免费在线观看 | 91精品视频在线 | 视频福利在线观看 | 中文字幕之中文字幕 | 国产涩涩网站 | 免费精品国产va自在自线 | 在线观看www.| 日韩欧美高清一区二区 | 在线观看日本高清mv视频 | 亚洲精品乱码久久久久久高潮 | 99精品国自产在线 | 国色综合 | 久久免费视频这里只有精品 | 在线免费试看 | 欧美另类tv | 亚洲黄色网络 | 又色又爽又黄高潮的免费视频 | 久一在线 | 日韩综合精品 | 91视频在线免费 | 爱av在线网 | 久久综合加勒比 | 丁香六月中文字幕 | 网站你懂的 | 久久久在线观看 | 免费观看成人网 | 91精品久久久久久久91蜜桃 | 久久免费成人 | 中文字幕第一页在线视频 | 日韩一二区在线观看 | 国产亚洲精品xxoo | 久久久精品一区二区三区 | 五月天国产精品 | 在线三级av | 国产91aaa| 九九精品视频在线观看 | 久久久久久久久久久免费 | 999久久久久久久久久久 | 五月婷婷,六月丁香 | av先锋影音少妇 | 久草在线免费新视频 | 亚洲成人动漫在线观看 | 欧美精品久久久久久久久久 | 久艹视频免费观看 | 久久精品综合视频 | 日日噜噜噜噜夜夜爽亚洲精品 | 免费观看特级毛片 | 久久国产精品99久久人人澡 | 日韩午夜视频在线观看 | 在线视频18在线视频4k | 综合五月 | 视频一区在线播放 | 国产福利专区 | 干亚洲少妇 | 午夜视频一区二区 | 国产精品18久久久久白浆 | 麻豆视频免费在线观看 | 美女精品网站 | 欧美男同网站 | 国产伦精品一区二区三区无广告 | 一级免费看视频 | 在线免费av网站 | 亚洲视频在线免费观看 | av在线播放一区二区三区 | 欧美一区三区四区 | 国产精品一区二区三区四 | 黄色av一区二区 | 亚洲精品免费观看视频 | av免费在线观看网站 | 色午夜影院 | 国产性天天综合网 | 日本午夜免费福利视频 | 亚洲久草视频 | 超级碰碰碰免费视频 | 久久久综合精品 | 麻豆视频免费网站 | 天天干天天射天天操 | 黄色亚洲 | 蜜臀久久99精品久久久久久网站 | 午夜av免费看 | 成人免费看电影 | 精品中文字幕在线观看 | 欧美日韩高清在线一区 | 天天干,天天干 | 玖玖999| 91亚洲欧美激情 | 欧美最新大片在线看 | 免费aa大片| 日韩欧美不卡 | 国产在线观看 | 狠狠狠色丁香综合久久天下网 | 国产99久久久国产精品免费看 | 亚洲精品91天天久久人人 | 天天天天爱天天躁 | 久久亚洲人 | 伊人永久在线 | 婷婷久操 | 日韩区在线观看 | 欧美做受69 | 欧美性爽爽 | 中文字幕精品久久 | 久久久久欧美精品999 | 91中文字幕| 国产精品视频免费看 | 精品国产_亚洲人成在线 | 日韩美女一级片 | 丝袜美腿亚洲综合 | 精品久久网| 五月天最新网址 | 五月综合在线观看 | 天天射天天干天天爽 | 国产精品欧美精品 | 免费看麻豆 | 91视频-88av | 99久久爱 | 黄色精品视频 | 在线观看av的网站 | 在线看v片| 能在线观看的日韩av | 黄色免费高清视频 | 天天综合天天综合 | 欧美日韩不卡在线观看 | 国产日韩视频在线 | 日本在线中文 | 99情趣网视频 | 国产一二三区av | 98超碰人人 | 日韩一区二区三区不卡 | 高清av影院| 国产一区二区电影在线观看 | 日韩91av | 99久久精品午夜一区二区小说 | 丰满少妇在线观看 | 日韩免费电影在线观看 | 在线观看 国产 | 黄污网| 操操碰 | 西西444www大胆无视频 | 一区二区三区四区五区在线 | 伊人中文网 | 日韩 在线观看 | 视频一区二区在线 | 亚洲视频资源在线 | 日韩精品免费一区二区在线观看 | 国产精品a久久久久 | 国内精品久久久久影院一蜜桃 | 国产精品久久久久久久久久免费看 | 中文字幕高清免费日韩视频在线 | 日韩视频一区二区在线观看 | 久久久久一区二区三区四区 | 亚洲天堂自拍视频 | 免费在线黄色av | 午夜男人影院 | 女人高潮一级片 | 成人av片在线观看 | 在线亚州 | 黄色中文字幕在线 | 91精品久久久久久久久久入口 | 色婷婷福利 | 中文字幕黄色网址 | 国产成免费视频 | 99久久精品午夜一区二区小说 | 色婷婷狠| 国产一区二区在线播放视频 | 97热久久免费频精品99 | 96视频免费在线观看 | 成人理论电影 | 黄色大片日本 | 欧美日韩精品免费观看视频 | 成人在线视频在线观看 | 人人爽人人爽人人 | 人人爽人人香蕉 | 日韩黄色中文字幕 | 国内精品视频免费 | 欧美一区二区在线免费看 | 超碰99在线| 日韩精品在线观看视频 | 97超碰在线人人 | 亚洲精品中文在线观看 | 国产成人精品在线播放 | 91精品小视频 | 毛片1000部免费看 | 麻豆91在线看 | 欧美成人91 | 91精品视屏| 色香蕉在线 | 免费日韩 精品中文字幕视频在线 | 在线看av网址| 在线观看中文字幕2021 | 国产黄色大片 | 欧洲视频一区 | 久久免费黄色大片 | 91久久国产露脸精品国产闺蜜 | 中文字幕无吗 | 中文av影院 | 久久精品国产精品亚洲 | 欧美在线观看视频一区二区三区 | 右手影院亚洲欧美 | 欧美激情另类文学 | 亚洲一区在线看 | 久久久精品视频成人 | 看毛片网站 | 久久噜噜少妇网站 | 欧美日韩视频免费 | www.久草.com| 国产情侣一区 | 精品久久久久久久久久久久久 | 日韩久久精品一区二区 | 国产中文字幕亚洲 | 久久中文视频 | 久久久久成人免费 | 色综合天天狠天天透天天伊人 | 午夜精品av | 美女免费网站 | www.香蕉视频| 99视频久久 | 午夜影院一级 | 国产一级小视频 | 日韩有码在线观看视频 | 国产精品一区在线观看你懂的 | 国产三级av在线 | 麻豆视频在线免费观看 | www.日本色| 97理论电影 | 亚洲黄色激情小说 | 国产成视频在线观看 | 一级理论片在线观看 | 国产一区黄色 | 亚洲午夜久久久影院 | 国产成人精品久久久 | 国产色秀视频 | 九九精品无码 | 国产成人一区二区啪在线观看 | 久久精品综合网 | 国产一级黄色片免费看 | 97视频免费播放 | 综合久久影院 | 日韩国产精品一区 | 天天性天天草 | 国产 欧美 日产久久 | 精品免费久久久久久 | 国产美女视频网站 | 中文字幕在线成人 | 国产精品久久久久久久久久ktv | 在线av资源 | 国产专区欧美专区 | 综合精品久久久 | 最新在线你懂的 | 一区二区三区在线影院 | 人人插人人草 | 91成人在线观看喷潮 | 亚洲一二三区精品 | 在线高清av| 久艹在线播放 | 91免费网站在线观看 | 五月婷婷国产 | 激情欧美丁香 | 国产精品少妇 | 人人舔人人 | 色94色欧美 | 欧美一级黄色片 | 一区在线电影 | 最新亚洲视频 | 亚洲激情在线观看 | 久久首页 | 国产中文字幕在线视频 | 亚洲精品动漫成人3d无尽在线 | 黄色在线视频网址 | 日韩视频在线观看视频 | 久久激情视频免费观看 | 久久av免费 | 麻豆传媒视频在线 | 91成人精品一区在线播放 | 成人午夜片av在线看 | 丰满少妇久久久 | 中文字幕在线有码 | 国产精品久久久久久爽爽爽 | 黄色大片免费播放 | 91成人精品一区在线播放69 | 亚洲视频一 | 日本公妇在线观看高清 | 久久曰视频 | 国产精品美女在线观看 | 五月婷婷综合激情网 | 久久久精品 一区二区三区 国产99视频在线观看 | 午夜av在线电影 | 综合婷婷丁香 | 亚洲精品视频免费 | 最近高清中文字幕 | 亚洲欧美乱综合图片区小说区 | wwwwwww黄 | 精品自拍sae8—视频 | 香蕉视频免费在线播放 | 国产成人在线看 | 亚洲天堂网视频在线观看 | 天天操狠狠操 | 91经典在线| 丁香视频免费观看 | 人人舔人人射 | 国产传媒中文字幕 | 久草在线播放视频 | 亚洲一区二区三区四区在线视频 | 色www精品视频在线观看 | 九九色网 | 五月天婷亚洲天综合网鲁鲁鲁 | 免费看亚洲毛片 | 亚洲成人家庭影院 | www.夜夜操 | 久久一区国产 | 一区国产精品 | 日本公乱妇视频 | 免费看日韩片 | 亚洲精品久 | 色欲综合视频天天天 | 青青久草在线视频 | 最近日本韩国中文字幕 | 色瓜| 国产一级片直播 | 日韩不卡高清 | 国产精品一区二区久久精品爱微奶 | 亚洲精品美女视频 | 久久一久久| 中文字幕免费国产精品 | 欧美另类高清 videos | 婷婷六月激情 | 91大神精品视频 | 日韩区视频 | 日本三级中文字幕在线观看 | 天天天插 | 午夜美女视频 | 黄色综合 | 国产99久久久精品 | 欧美日韩一区二区三区视频 | 国产精品一区二区吃奶在线观看 | 午夜精品久久久久99热app | 成人免费观看a | 制服丝袜一区二区 | а天堂中文最新一区二区三区 | 人人爱爱| 五月激情六月丁香 | 色婷婷狠狠18 | 免费看一级特黄a大片 | 亚洲黄色免费观看 | 久久高清国产视频 | 国产精品免费久久久久久久久久中文 | 天天躁日日躁狠狠躁av中文 | 国产精品美女久久久久久 | 午夜精品视频福利 | 亚洲无吗av | 久久久国产精品网站 | 国产精品99久久久久人中文网介绍 | 最近日韩中文字幕中文 | 久久久这里有精品 | 久久在视频 | 一级欧美一级日韩 | 欧美色综合天天久久综合精品 | 免费视频99 | 少妇bbw揉bbb欧美 | 久久国产精品视频 | 欧美一级性 | 国产成人一区二区在线观看 | 国外调教视频网站 | 日韩亚洲国产中文字幕 | 精品国产一区二区三区久久久蜜月 | 青青草视频精品 | 亚洲1区在线 | 日日射av| www.香蕉视频在线观看 | 青春草视频在线播放 | 中文字幕中文字幕在线中文字幕三区 | 午夜免费在线观看 | 久久午夜网 | 国产成人精品久久久 | 免费在线观看黄色网 | 日韩二区在线观看 | 99精品一级欧美片免费播放 | 国产成人精品久久亚洲高清不卡 | 亚洲国产精品成人av | 日韩网站在线免费观看 | 国产r级在线观看 | 国产精品久久久久久久毛片 | 一区二区三区在线免费观看视频 | 韩日精品在线 | 91在线视频精品 | 国产精品毛片完整版 | 激情丁香综合五月 | 国产麻豆剧传媒免费观看 | 国产精品永久免费在线 | 久久精品首页 | 在线观看国产区 | 91在线网址 | 人人舔人人干 | 欧美综合在线观看 | av大全在线免费观看 | 国产精久久久久久久 | 久久精品久久99精品久久 | 久久午夜网 | 四虎免费在线观看 | 国产精品成人免费精品自在线观看 | 中文字幕视频免费观看 | 狠狠插天天干 | 狠狠干.com| 草莓视频在线观看免费观看 | 日韩二区在线播放 | av在线播放国产 | 一级成人免费视频 | 亚洲高清激情 | 久久婷婷丁香 | 国产在线视频一区 | 九九热视频在线免费观看 | 国产视频在线观看一区 | 麻豆久久久久 | 中文字幕色播 | 婷婷婷国产在线视频 | 欧美综合在线视频 | 成年人在线看片 | 美女久久久久久久 | 国产亚洲精品久久19p | 国产欧美久久久精品影院 | 国产中文字幕国产 | 97国产在线观看 | 日韩av有码在线 | 欧美成年人在线视频 | 99久久日韩精品视频免费在线观看 | 在线看片成人 | 九七视频在线 | 日韩av有码在线 | 成人欧美日韩国产 | 成人黄色电影在线观看 | 久久噜噜少妇网站 | 狠狠操天天操 | 一区二区三区日韩视频在线观看 | 欧美色精品天天在线观看视频 | 欧美一级大片在线观看 | 婷婷av综合 | 免费av观看网站 | 免费看亚洲毛片 | 欧美日韩免费视频 | 成人黄色电影在线观看 | 中文字幕乱码视频 | 又爽又黄又刺激的视频 | 欧美日本不卡 | 免费在线激情电影 | 99精品网站 | 国产一区在线免费 | 免费观看黄 | 国产精品美乳一区二区免费 | 国产精品中文久久久久久久 | 日韩电影一区二区在线观看 | 91黄色在线视频 | 奇米网777 | 天天色中文| 日日夜夜中文字幕 | 91在线免费观看网站 | 国产精品久久久久久模特 | 国产爽妇网| 亚洲一区久久久 | 不卡视频在线看 | 欧美精品中文 | 五月天婷婷在线观看视频 | 亚洲欧美乱综合图片区小说区 | 天天操天天操一操 | 亚洲国产精品成人va在线观看 | 亚洲综合视频在线播放 | 国产精品久久久久久妇 | 婷婷网站天天婷婷网站 | 麻豆小视频在线观看 | h文在线观看免费 | 福利一区在线 | 99久久这里有精品 | 在线观看视频免费播放 | 麻豆系列在线观看 | 免费视频黄 | 国产高清综合 | 1024久久| 天天操天天操天天操天天操天天操天天操 | 婷婷精品国产欧美精品亚洲人人爽 | 99精品国产高清在线观看 | 欧美日韩p片 | 亚洲黄色免费电影 | 亚洲精品国偷拍自产在线观看 | 丁香色婷婷| av福利电影| 国产一区自拍视频 | 97色国产| 成人在线观看网址 | 日本精品一区二区三区在线观看 | 精品久久久久久久 | 日韩网站在线播放 | 二区三区在线 | 色吊丝在线永久观看最新版本 | 九色自拍视频 | 国产精品国产三级国产专区53 | 成人午夜影院 | 精品一区二区三区久久 | 国产99久久久国产精品免费二区 | 精品久久久久久综合 | 九九免费在线看完整版 | 国产精品第52页 | 九九九九九国产 | 中文字幕精品一区久久久久 | 麻豆一精品传二传媒短视频 | 欧美成人在线免费观看 | 黄色影院在线免费观看 | 日韩一区二区三 | 欧美 亚洲 另类 激情 另类 | 一区二区三区在线免费播放 | 国产日产在线观看 | av在线播放快速免费阴 | 青青色影院 | 一区二区三区在线免费观看视频 | 亚洲欧美国产日韩在线观看 | 91在线看| 国产视频69 | 国产丝袜在线 | 天天综合天天做天天综合 | 国产精品视频久久久 | 日韩一区二区免费视频 | 在线视频电影 | 国内毛片毛片 | 91成人网页版 | 日韩一二区在线 | 干干日日 | 久久男人影院 | 日韩在线观看视频一区二区三区 | 欧美日韩免费观看一区=区三区 | 亚洲欧美国产精品18p | 亚洲污视频| 欧美韩国日本在线 | 中文字幕亚洲精品在线观看 | h网站免费在线观看 | 国产成人av网| 综合国产在线 | 能在线观看的日韩av | 国产精品免费一区二区 | 久草在线视频中文 | 韩国在线一区 | 最近中文字幕完整高清 | 日韩美在线 | 国际av在线 | 97偷拍在线视频 | 国产专区免费 | av夜夜操 | 中文字幕视频一区二区 | 黄色大片av | 亚洲精品国产品国语在线 | 日韩在线不卡视频 | 亚洲欧洲成人精品av97 | 久久99国产精品久久99 | 日韩精品亚洲专区在线观看 | 久久久久免费电影 | 国产色在线视频 | 久久精品首页 | 黄色免费观看网址 | 91免费国产在线观看 | 丁香花在线视频观看免费 | 黄色免费网站 | 五月婷婷综合久久 | 婷婷在线五月 | 欧美午夜a | 中文字幕成人网 | 国产午夜麻豆影院在线观看 | 国产久视频 | 久久99精品国产91久久来源 | 国模精品在线 | 午夜 在线 | 五月天天色 | 国产不卡一二三区 | 97小视频 | 中文字幕在线字幕中文 | 五月激情av | 国产精品黄色在线观看 | 久久久久久电影 | 日韩 国产 | 激情综合亚洲 | 夜夜操综合网 | 欧美日韩亚洲一 | 伊人五月天av| 91av在线不卡 | 99久久精品久久久久久清纯 | 伊人影院得得 | 美女视频黄色免费 | 成人av影视| 综合网伊人 | 欧美人zozo | 国产99一区二区 | 五月天综合激情网 | 日韩在线观看网址 | 日日草天天草 | 亚洲国产精品激情在线观看 | 色爱成人网 | 蜜桃传媒一区二区 | 亚洲精品伦理在线 | 国产精品第二十页 | 天天摸夜夜操 | 91精品视频导航 | 国产精品视频不卡 | 中文在线字幕免费观 | 免费黄色在线播放 | 91色一区二区三区 | 久久精品欧美日韩精品 | 欧美国产91 | 欧美日韩视频观看 | 亚洲情影院| 国产毛片aaa | 国产一区久久久 | 免费黄色一区 | 99精品观看 | 国产裸体永久免费视频网站 | 天天看天天干 | 高清国产一区 | 成人超碰97 | 日韩精品影视 | 亚洲黄色免费网站 | 九九99视频| 久久视频在线 | 中文字幕在线不卡国产视频 | 国产日本亚洲高清 | 日本久久精 | 国产精品久久久久永久免费 | 国产h片在线观看 | 国产精品久久久久久久7电影 | 六月色婷 | 91pony九色丨交换 | 成人黄色资源 | 瑞典xxxx性hd极品 | 免费看一级黄色大全 | 国产一级免费电影 | 免费色婷婷 | 欧美精品在线视频 | 正在播放国产一区 | 99精品国产99久久久久久福利 | 久草在线官网 | 91专区在线观看 | 天天干天天拍天天操天天拍 | 狠狠干天天色 | 国产精品日韩在线 | 深爱激情五月网 | 久久情侣偷拍 | 五月婷婷操 | 欧美一级裸体视频 | 久久久国际精品 | 中文在线中文资源 | 天天操天天爱天天干 | 五月婷婷丁香在线观看 | 欧美成人h版电影 | 狠狠色狠狠色合久久伊人 | 91精品国产自产91精品 | 欧美性视频网站 | 国产精品原创视频 | 香蕉97视频观看在线观看 | a级国产乱理论片在线观看 伊人宗合网 | 天天干天天操天天爱 | 日韩伦理片hd | 亚洲综合激情 | av中文字幕免费在线观看 | 精品国内自产拍在线观看视频 | 久久伊人精品一区二区三区 | 久草在线免费电影 | 日韩精品一区电影 | 国产精品乱码一区二三区 | 国产精品99久久久久久久久 | 国产操在线 | 成人黄色小说视频 | 手机av在线网站 | 人人涩| 欧美激情视频一区二区三区 | 日韩极品在线 | 91激情在线视频 | 五月婷婷六月丁香在线观看 | 国内久久看 | 天天干,天天插 | 在线观看视频99 | www.五月天婷婷.com | bbbb操bbbb| 久久久精华网 | 天天色天天射天天综合网 | 天天天干天天天操 | 久久综合五月天婷婷伊人 | 国产尤物在线 | 久久久午夜视频 | 国产精品3 | 成人免费在线播放视频 | 中文字幕视频播放 | 亚洲激情一区二区三区 | 久久69av | 国内视频在线观看 | 久久久黄色 | 91在线精品播放 | 久久人人爽人人爽 | 欧美9999 | 国产又粗又猛又爽又黄的视频免费 | 亚洲综合导航 | 伊人久久五月天 | 精品国偷自产国产一区 | 欧美一二三在线 | 国产久草在线观看 | 日韩二区三区在线 | 不卡电影免费在线播放一区 | 亚洲精品午夜久久久久久久久久久 | 亚洲成色777777在线观看影院 | 日韩毛片在线免费观看 | 四虎在线视频免费观看 | 在线一区观看 | 亚洲91av| 久久色视频 | 天海翼一区二区三区免费 | 91视频传媒| 91综合久久一区二区 | 亚洲午夜久久久久久久久电影网 | 日本精品视频在线 | 色资源在线 | 午夜精品久久久久久久99热影院 | 国产黄色av | 国产一级二级三级在线观看 | 日韩在线网址 | 免费观看一区二区 | 国产在线播放一区二区三区 | 在线91精品 | 欧美日韩裸体免费视频 | 美女又爽又黄 | 日韩性xxxx | 麻豆视频国产 | 成年人精品 | www.亚洲视频.com | 超碰公开在线观看 | 日韩女同av | 亚洲午夜电影网 | 国产精品一区二区三区在线免费观看 | 婷婷九月丁香 | 久久亚洲福利 | 激情www| 日韩av电影免费观看 | 91久久一区二区 | 精品色999| 亚洲精品国产精品久久99 | 日韩av成人在线观看 | 91av久久| 亚洲理论在线观看 | 国产中文欧美日韩在线 | 日韩在线观看你懂的 | 婷婷丁香在线观看 | 成人a视频在线观看 | 久久久精品国产一区二区 | 亚洲欧美视频在线播放 | 亚洲无毛专区 | 免费裸体视频网 | 成人av资源网 | 在线看片一区 | 欧美a视频在线观看 | 天天操天天干天天干 | 日韩三级视频 | 97综合在线 | 91av久久| 亚洲国产欧美一区二区三区丁香婷 | 久青草影院 | 激情网在线观看 | 天天玩天天干 | 久久免费视频2 | 不卡av在线免费观看 | 日韩午夜av | 91精品亚洲影视在线观看 | 亚洲一区二区三区四区精品 | 日韩色中色 | 日本性久久 | 91精品伦理 | 欧美成人一区二区 | 免费看黄20分钟 | 视频精品一区二区三区 | 国产成人免费在线 | 亚洲精品国产第一综合99久久 | 99在线视频免费观看 | 国产精品久久久999 国产91九色视频 | 欧美日韩免费在线观看视频 | 日韩在线观看电影 | 免费看污污视频的网站 | 夜夜夜精品 | 成人a v视频 | 久草在线免费看视频 | 日韩精品视频在线观看网址 | 国产精品久久久久久久久久东京 | 麻豆视频免费播放 | 娇妻呻吟一区二区三区 | 99久久精品国产系列 | 日本精品视频一区二区 | 91av久久| 国产小视频91 | 日本韩国中文字幕 | 国产极品尤物在线 | 亚洲在线观看av | 久草综合视频 | 亚洲精品在线免费播放 | 91在线免费公开视频 | 狠狠艹夜夜干 | 亚洲五月激情 | 国语自产偷拍精品视频偷 | 久久久久久久久久久高潮一区二区 | 狠狠干夜夜| 色99导航 | 国产精品国产三级国产aⅴ9色 | 日韩免费二区 | 99久久久久久久 | 色偷偷av男人天堂 | 狠狠做六月爱婷婷综合aⅴ 日本高清免费中文字幕 | 69热国产视频 | 亚洲视频网站在线观看 | 色悠悠久久综合 | 精品久久久久久综合 | 国产视频二区三区 | 久久久亚洲国产精品麻豆综合天堂 | 黄色一级免费电影 | 一本一道久久a久久精品 | 成人免费在线观看av | 久久免费视频7 | 中文字幕有码在线 | 国产91在线观 | 国产一区二区三区免费在线观看 | 天天操天天色天天射 | 亚洲国产三级在线 | 五月天婷婷免费视频 | 久久精品电影 | 久久精视频 | 91高清不卡| 国产精品高潮呻吟久久av无 | 午夜av免费在线观看 | 欧美在线视频免费 | 日韩精品久久久免费观看夜色 | 亚洲永久字幕 | 欧美日韩一二三四区 | 亚洲国产日韩在线 | 久久久在线 | 色婷婷久久一区二区 | 99色精品视频 | 99爱爱| 久久6精品 | 香蕉在线播放 | 激情五月av | 日韩电影久久 | 欧美性色xo影院 | 久久99国产精品免费网站 | 久久精品国产一区二区 | 天天色播| 国产伦理一区二区 | 欧美精品久久久久久久久老牛影院 | 国产一级片免费观看 | 91最新在线视频 | 99视频在线播放 | 中文字幕亚洲综合久久五月天色无吗'' | 国产一区二区久久 | 伊人中文在线 | 91麻豆高清视频 | 久要激情网 | 亚洲精品日韩av | 国产高清视频在线播放一区 | 亚洲国产小视频在线观看 | 亚洲视频专区在线 | 激情视频一区 | 国内精品免费久久影院 | 久久精品免费电影 | 伊人久久在线观看 | 国产黄a三级三级三级三级三级 | 国产乱码精品一区二区蜜臀 | 人人爽人人爽人人片av免 | 久久tv视频 | 九九精品毛片 | 久久精品99国产精品亚洲最刺激 | 欧美少妇xxx|