I am confused when we need to define another function we can give it a different name. But on LeetCode discussion, I found a popular post in which there are two functions with same name, but having different parameters. Show
Alan Birtles 28.8k4 gold badges27 silver badges52 bronze badges asked Sep 4, 2020 at 6:44
1
The is the one of the most basic feature of C++: function overloading. In C you can't have two functions with the same name, at all. In C++, it's entirely possible as long as the function function signature is different, ie two functions having the same name but different set of parameters. https://en.wikipedia.org/wiki/Function_overloading answered Sep 4, 2020 at 6:47
artmartm 16.9k4 gold badges33 silver badges51 bronze badges 4 What you are looking at is called "Function overloading" in C++. The c++ compiler creates signatures based on the declaration of the function. You can have entirely different signatures of a function with the same name. In the example posted by you, the signature changes because of the difference in the parameters passed. here is what Signature stands for : the information about a function that participates in overload resolution (13.3): its parameter-type-list (8.3.5) and, if the function is a class member, the cv-qualifiers (if any) on the function itself and the class in which the member function is declared. answered Sep 4, 2020 at 7:41
In a strongly typed language, the parser can (in principle) make the difference between functions with the same name but a different argument list (number and type of the arguments), at function-declaration time as well as function-call time. This is called function overloading and also applies to class methods. C++ supplies this feature. In some cases, there are ambiguities and the compiler will tell you. In C++ you cannot declare functions that only differ by their return type. answered Sep 4, 2020 at 8:15
Yves DaoustYves Daoust 55.3k8 gold badges43 silver badges99 bronze badges General Questions¶Is there a source code level debugger with breakpoints, single-stepping, etc.?¶Yes. Several debuggers for Python are described below, and the built-in function The pdb module is a simple but adequate console-mode debugger for Python. It is part of the standard Python library, and is 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 pywin32 project and as a part of the ActivePython distribution. Eric is an IDE built on PyQt and the Scintilla editing component. trepan3k is a gdb-like debugger. Visual Studio Code is an IDE with debugging tools that integrates with version-control software. There are a number of commercial Python IDEs that include graphical debuggers. They include:
Are there tools to help find bugs or perform static analysis?¶Yes. Pylint and Pyflakes do basic checking that will help you catch bugs sooner. Static type checkers such as Mypy, Pyre, and Pytype can check type hints in Python source code. 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 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. The following packages can help with the creation of console and GUI executables:
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. 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 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: You can do a similar thing in a nested scope using the >>> def foo(): ... x = 10 ... def bar(): ... nonlocal x ... print(x) ... x += 1 ... bar() ... print(x) >>> foo() 10 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 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 >>> squares[2]() 16 >>> squares[4]() 16 This happens because >>> 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 >>> squares = [] >>> for x in range(5): ... squares.append(lambda n=x: n**2) Here, >>> 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 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:
It is sometimes necessary to move imports to a function or class to avoid problems with circular imports. Gordon McMillan says:
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 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] = value return mydict The first time you call this function, 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
Because of this feature, it is good programming practice to not use mutable objects as default values. Instead, use 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 can only provide two parameters and optionally pass _cache by keyword def expensive(arg1, arg2, *, _cache={}): if (arg1, arg2) in _cache: return _cache[(arg1, arg2)] # Calculate the value result = ... expensive computation ... _cache[(arg1, arg2)] = result # Store result in the cache return 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 def f(x, *args, **kwargs): ... kwargs['width'] = '14.3c' ... 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 kind 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(42, bar=314, extra=somevar) the values 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 There are two factors that produce this result:
After the call to If we instead assign an immutable object to >>> 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
Some operations (for example However, there is one class of operations where the same operation sometimes has different behaviors with different types: the augmented assignment operators. For example, In other words:
If you want to know if two variables refer to the same object or not, you can use the 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.
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 def linear(a, b): def result(x): return a * x + b return result Or using a callable object: class linear: def __init__(self, a, b): self.a, self.b = a, b def __call__(self, x): return self.a * x + self.b In both cases, gives
a callable object where 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__ inherited def __call__(self, x): return self.a * (x ** self.b) Object can encapsulate state for several methods: class counter: value = 0 def set(self, x): self.value = x def up(self): self.value = self.value + 1 def down(self): self.value = self.value - 1 count = counter() inc, dec, reset = count.up, count.down, count.set Here How do I copy an object in Python?¶In general, try Some objects can be copied more easily. Dictionaries have a Sequences can be copied by slicing: How can I find the methods or attributes of an object?¶For an instance x of a user-defined 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 >>> class A: ... pass ... >>> B = A >>> a = B() >>> b = a >>> print(b) <__main__.A object at 0x16D07CC> >>> print(a) <__main__.A object 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:
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: not: The same is true of the various assignment operators ( Is there an equivalent of C’s “?:” ternary operator?¶Yes, there is. The syntax is as follows: [on_true] if [expression] else [on_false] x, y = 50, 25 small = x if x < y else y Before this syntax was introduced in Python 2.5, a common idiom was to use logical operators: [expression] and [on_true] or [on_false] However, this idiom is unsafe, as it can give wrong results when on_true has a false boolean value. Therefore, it is always better to use the Is it possible to write obfuscated one-liners in Python?¶Yes. Usually this is done by nesting from functools import reduce # Primes < 1000 print(list(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(list(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! What does the slash(/) in the parameter list of a function mean?¶A slash in the argument list of a function denotes
that the parameters prior to it are positional-only. Positional-only parameters are the ones without an externally usable name. Upon calling a function that accepts positional-only parameters, arguments are mapped to parameters based solely on their position. For example, >>> help(divmod) Help on built-in function divmod in module builtins: divmod(x, y, /) Return the tuple (x//y, x%y). Invariant: div*y + mod == x. The
slash at the end of the parameter list means that both parameters are positional-only. Thus, calling >>> divmod(x=3, y=4) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: divmod() takes no keyword arguments 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: 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 == (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 There are few real use cases for How do I get int literal attribute instead of SyntaxError?¶Trying to lookup an >>> 1.__class__ File "<stdin>", line 1 1.__class__ ^ SyntaxError: invalid decimal literal The solution is to separate the literal from the period with either a space or parentheses. >>> 1 .__class__ <class 'int'> >>> (1).__class__ <class 'int'> How do I convert a string to a number?¶For integers, use the built-in By default, these interpret the number as decimal, so that Do not use the built-in function
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 How do I modify a string in place?¶You can’t, because strings are immutable. In most situations, you should
simply construct a new string from the various parts you want to assemble it from. However, if you need an object with the ability to modify in-place unicode data, try using an >>> import io >>> s = "Hello, world" >>> sio = io.StringIO(s) >>> sio.getvalue() 'Hello, world' >>> sio.seek(7) 7 >>> sio.write("there!") 6 >>> sio.getvalue() 'Hello, there!' >>> import array >>> a = array.array('u', s) >>> print(a) array('u', 'Hello, world') >>> a[0] = 'y' >>> print(a) array('u', 'yello, world') >>> a.tounicode() 'yello, world' How do I use strings to call functions/methods?¶There are various techniques.
Is there an equivalent to Perl’s chomp() for removing trailing newlines from strings?¶You can use >>> 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 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 For more complicated input parsing, regular expressions are more powerful than C’s What does ‘UnicodeDecodeError’ or ‘UnicodeEncodeError’ error mean?¶See the Unicode HOWTO. Performance¶My program is too slow. How do I speed it up?¶That’s a tough one, in general. First, here are a list of things to remember before diving further:
That being said, there are many tricks to speed up Python code. Here are some general principles which go a long way towards reaching acceptable performance levels:
If you have reached the limit of what pure Python can allow, there are tools to take you further away. For example, Cython can compile a slightly modified version of Python code into a C extension, and can be used on many different platforms. Cython can take advantage of compilation (and optional type annotations) to make your code significantly faster than when interpreted. If you are confident in your C programming skills, you can also write a C extension module yourself. What is the most efficient way to concatenate many strings together?¶
To accumulate many chunks = [] for s in my_strings: chunks.append(s) result = ''.join(chunks) (another reasonably
efficient idiom is to use To accumulate many result = bytearray() for b in my_bytes_objects: result += b Sequences (Tuples/Lists)¶How do I convert between tuples and lists?¶The type constructor For example, The type constructor 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 Using negative indices can be very convenient. For example How do I iterate over a sequence in reverse order?¶Use the 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. How do you remove duplicates from a list?¶See the Python Cookbook for a long discussion of many ways to do this: 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 set keys (i.e. they are all hashable) this is often faster mylist = list(set(mylist)) This converts the list into a set, thereby removing duplicates, and then back into a list. How do you remove multiple items from a list¶As with removing duplicates, explicitly iterating in reverse with a delete condition is one possibility. However, it is easier and faster to use slice replacement with an implicit or explicit forward iteration. Here are three variations.: mylist[:] = filter(keep_function, mylist) mylist[:] = (x for x in mylist if keep_condition) mylist[:] = [x for x in mylist if keep_condition] The list comprehension may be fastest. 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 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 How do I create a multidimensional list?¶You probably tried to make a multidimensional array like this: 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 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; NumPy 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] 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 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: 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 >>> 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
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 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, use the Isorted = L[:] Isorted.sort(key=lambda s: int(s[10:15])) How can I sort one list by values from another list?¶Merge them into an iterator 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 = sorted(pairs) >>> pairs [("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')] >>> result = [x[1] for x in pairs] >>> result ['else', 'sort', 'to', 'something'] 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 What is a method?¶A method is a function on some object 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 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 Note that from collections.abc import Mapping class P: pass class C(P): pass Mapping.register(P) >>> c = C() >>> isinstance(c, C) # direct True >>> isinstance(c, P) # indirect True >>> isinstance(c, Mapping) # virtual True # Actual inheritance chain >>> type(c).__mro__ (<class 'C'>, <class 'P'>, <class 'object'>) # Test for "true inheritance" >>> Mapping in type(c).__mro__ False Note that most programs do not use def search(obj): if isinstance(obj, Mailbox): ... # code to search a mailbox elif isinstance(obj, Document): ... # code to search a document elif ... A better approach is to define a class Mailbox: def search(self): ... # code to search a mailbox class Document: def search(self): ... # code to search a document obj.search() What is delegation?¶Delegation is an object oriented technique (also called a design pattern). Let’s say you have an object 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 = outfile def write(self, s): self._outfile.write(s.upper()) def __getattr__(self, name): return getattr(self._outfile, name) Here the Note that for more general cases delegation can get trickier. When attributes must be set as well as retrieved, the class must define a class X: ... def __setattr__(self, name, value): self.__dict__[name] = value ... Most
How do I call a method defined in a base class from a derived class that extends it?¶Use the built-in class Derived(Base): def meth(self): super().meth() # calls Base.meth In the example, How can I organize my code to make it easier to change the base class?¶You could assign the base class to an alias and derive from the alias. 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: class Base: ... BaseAlias = Base class Derived(BaseAlias): ... 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__ called def __init__(self): C.count = C.count + 1 def getcount(self): return C.count # or return self.count
Caution: within a method of C, an assignment like
Static methods are possible: class C: @staticmethod def 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 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 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 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 Despite the cycle collector, it’s still a
good idea to define an explicit Another way to avoid cyclical references is to use the Finally, if your 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(1000) 13901272 >>> id(2000) 13901272 The two ids belong to different integer
objects that are created before, and deleted immediately after execution of the >>> a = 1000; b = 2000 >>> id(a) 13901272 >>> id(b) 13891296 When can I rely on identity tests with the is operator?¶The The most important property of an identity test is that an object is always identical to itself, However, identity tests can only be substituted for equality tests when object identity is assured. Generally, there are three circumstances where identity is guaranteed: 1) Assignments create new names but do not change object identity. After the assignment 2) Putting an object in a container that stores object references does not change object
identity. After the list assignment 3) If an object is a singleton, it means that only one instance of that object can exist. After the assignments In most other circumstances, identity tests are inadvisable and equality tests are preferred. In particular, identity tests should not be used to check constants such as
>>> a = 1000 >>> b = 500 >>> c = b + 500 >>> a is c False >>> a = 'Python' >>> b = 'Py' >>> c = b + 'thon' >>> a is c False Likewise, new instances of mutable containers are never identical: >>> a = [] >>> b = [] >>> a is b False In the standard library code, you will see several common patterns for correctly using identity tests: 1) As recommended by
PEP 8, an identity test is the preferred way to check for 2) Detecting optional arguments can be tricky when _sentinel = object() def pop(self, key, default=_sentinel): if key in self: value = self[key] del self[key] return value if default is _sentinel: raise KeyError(key) return default 3) Container implementations sometimes need to augment equality tests with identity tests. This prevents the code from being confused by objects such as For example, here is the implementation of def __contains__(self, value): for v in self: if v is value or v == value: return True return False How can a subclass control what data is stored in an immutable instance?¶When subclassing an immutable type, override the
All of these immutable classes have a different signature than their parent class: from datetime import date class FirstOfMonthDate(date): "Always choose the first day of the month" def __new__(cls, year, month, day): return super().__new__(cls, year, month, 1) class NamedInt(int): "Allow text names for some numbers" xlat = {'zero': 0, 'one': 1, 'ten': 10} def __new__(cls, value): value = cls.xlat.get(value, value) return super().__new__(cls, value) class TitleStr(str): "Convert str to name suitable for a URL path" def __new__(cls, s): s = s.lower().replace(' ', '-') s = ''.join([c for c in s if c.isalnum() or c == '-']) return super().__new__(cls, s) The classes can be used like this: >>> FirstOfMonthDate(2012, 2, 14) FirstOfMonthDate(2012, 2, 1) >>> NamedInt('ten') 10 >>> NamedInt(20) 20 >>> TitleStr('Blog: Why Python Rocks') 'blog-why-python-rocks' How do I cache method calls?¶The two principal tools for caching methods are The cached_property approach only works with methods that do not take any arguments. It does not create a reference to the instance. The cached method result will be kept only as long as the instance is alive. The advantage is that when an instance is no longer used, the cached method result will be released right away. The disadvantage is that if instances accumulate, so too will the accumulated method results. They can grow without bound. The lru_cache approach works with methods that have hashable arguments. It creates a reference to the instance unless special efforts are made to pass in weak references. The advantage of the least recently used algorithm is that the cache is bounded by the specified maxsize. The disadvantage is that instances are kept alive until they age out of the cache or until the cache is cleared. This example shows the various techniques: class Weather: "Lookup weather information on a government website" def __init__(self, station_id): self._station_id = station_id # The _station_id is private and immutable def current_temperature(self): "Latest hourly observation" # Do not cache this because old results # can be out of date. @cached_property def location(self): "Return the longitude/latitude coordinates of the station" # Result only depends on the station_id @lru_cache(maxsize=20) def historic_rainfall(self, date, units='mm'): "Rainfall on a given date" # Depends on the station_id, date, and units. The above example assumes that the station_id never changes. If the relevant instance attributes are mutable, the cached_property approach can’t be made to work because it cannot detect changes to the attributes. The lru_cache approach can be made to work, but the class needs to define the __eq__ and __hash__ methods so the cache can detect relevant attribute updates: class Weather: "Example with a mutable station identifier" def __init__(self, station_id): self.station_id = station_id def change_station(self, station_id): self.station_id = station_id def __eq__(self, other): return self.station_id == other.station_id def __hash__(self): return hash(self.station_id) @lru_cache(maxsize=20) def historic_rainfall(self, date, units='cm'): 'Rainfall on a given date' # Depends on the station_id, date, and units. Modules¶How do I create a .pyc file?¶When a module is imported for the first time (or when the source file has changed since the current compiled file was created) a One reason that a Unless the Running Python on a top level script is not considered an import and no If you need to create a The >>> import py_compile >>> py_compile.compile('foo.py') This will write the You can also automatically compile all files in a directory or directories using the How do I find the current module name?¶A module can find out its own
module name by looking at the predefined global variable 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:
from bar import bar_var foo_var = 1
from foo import foo_var bar_var = 2 The problem is that the interpreter will perform the following steps:
The last step fails, because Python isn’t done with interpreting The same thing happens when you use There are (at least) three possible workarounds for this problem. Guido van Rossum recommends avoiding all uses of Jim Roskind suggests performing steps in the following order in each module:
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 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 re-reading of a changed module, do this: import importlib import modname importlib.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 importlib >>> import cls >>> c = cls.C() # Create an instance of C >>> importlib.reload(cls) <module 'cls' from 'cls.py'> >>> isinstance(c, cls.C) # isinstance is false?!? False The nature of the problem is made clear if you print out the “identity” of the class objects: >>> hex(id(c.__class__)) '0x7352a0' >>> hex(id(cls.C)) '0x4198d0' What is another term for parameters of a function when it is called?The term parameter (sometimes called formal parameter) is often used to refer to the variable as found in the function definition, while argument (sometimes called actual parameter) refers to the actual input supplied at function call.
Which part of a function definition shows the function name return type and parameter list?A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.
Can different functions can have local variables with the same names?A local variable can be accessed from anywhere in the program. Different functions can have local variables with the same names.
Is it possible for a function to have parameters with default arguments and some without?It is possible for a function to have some parameters with default arguments and some without. A function's return data type must be the same as the function's parameter(s). One reason for using functions is to break programs into manageable units, or modules. You must furnish an argument with a function call.
|