Python Goog

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Bonus question: Tabs or Spaces?

"Author is a spaces zealot. 4 spaces per tab that is. Both answers are correct (spaces is more correct ). Incorrect answers are ""I don't know"", ""I don't care"", ""Both"", ""Does it matter""."

What is introspection/reflection and does Python support it?

"Introspection is the ability to examine an object at runtime. Python has a dir() function that supports examining the attributes of an object, type() to check the object type, isinstance(), etc. While introspection is passive examination of the objects, reflection is a more powerful tool where we could modify objects at runtime and access them dynamically. E.g. setattr() adds or modifies an object's attribute; getattr() gets the value of an attribute of an object. It can even invoke functions dynamically - getattr(my_obj, ""my_func_name"")()"

What's lambda?

"Lambda in Python is an anonymous function created at runtime. E.g. greeter = lambda x: ""Hello %s"" % x greeter(""Deko"") #prints Hello Deko"

When to use default values?

"Often you have a function that uses lots of default values, but on rare occasions you want to override the defaults. Default argument values provide an easy way to do this, without having to define lots of functions for the rare exceptions. As Python does not support overloaded methods/functions, default arguments are an easy way of ""faking"" the overloading behavior."

Why use generators?

"Simpler code, because the state of local variables and control flow are preserved for each call. A generator uses less memory than a function that creates an entire list of values at once. Good for doc string. Use ""Yields:"" rather than ""Returns:"" in the docstring for generator functions."

T/F Files should start with license boilerplate and a docstring

"T """"""A one line summary of the module or program, terminated by a period. Leave one blank line. The rest of this docstring should contain an overall description of the module or program. Optionally, it may also contain a brief description of exported classes and functions and/or usage examples. Typical usage example: foo = ClassFoo() bar = foo.FunctionBar() """""""

T/F If a class inherits from no other base classes, it should explicitly inherit from object?

"T If a class inherits from no other base classes, explicitly inherit from object. This also applies to nested classes. Inheriting from object is needed to make properties work properly in Python 2 and can protect your code from potential incompatibility with Python 3. It also defines special methods that implement the default semantics of objects including __new__, __init__, __delattr__, __getattribute__, __setattr__, __hash__, __repr__, and __str__. Yes: class SampleClass(object): pass class OuterClass(object): class InnerClass(object): pass class ChildClass(ParentClass): """"""Explicitly inherits from another class already."""""" No: class SampleClass: pass class OuterClass: class InnerClass: pass"

Write a simple decorator

"def paragraph_wrap(func): def func_wrapper(name): return ""<p>{0}</p>"".format(func(name)) return func_wrapper @paragraph_wrap def get_text(name): return ""lorem ipsum, {0} dolor sit amet"".format(name) print(get_text(""John""))"

Suppose lst is [2, 33, 222, 14, 25], What is lst[-1]?

25. Negative numbers mean that you count from the right instead of the left. So, lst[-1] refers to the last element, lst[-2] is the second-last, and so on.

"What is a ""callable""?"

A callable is an object we can call - function or an object implementing the __call__ special method. Any object can be made callable.

What is a dict and what's its most important limitation?

A dict is a structure akin a hash map. It stores key-value pairs, where keys are unique and it has O(1) access time. The most important limitation for a dict is that the keys must be hashable/immutable. Meaning, we can use a tuple as a key, but not a list.

What's a generator?

A generator is a callable object that acts as an iterable (object you can iterate in for cycles etc).

What are modules and packages in Python?

A module in Python is any file with .py extension. A package is a set of modules - a directory that contains one or many .py files, one of which is __init__.py Both modules and packages define functions, classes or any kind of software functionality. When we import something in Python, we import from packages and modules.

Lexical Scoping

A nested Python function can refer to variables defined in enclosing functions, but can not assign to them. Variable bindings are resolved using lexical scoping, that is, based on the static program text. Any assignment to a name in a block will cause Python to treat all references to that name as a local variable, even if the use precedes the assignment. If a global declaration occurs, the name is treated as a global variable. i = 4 def foo(x): def bar(): print(i, end='') # ... # A bunch of code here # ... for i in x: # Ah, i *is* local to foo, so this is what bar sees print(i, end='') bar() So foo([1, 2, 3]) will print 1 2 3 3, not 1 2 3 4.

What are virtualenvs?

A virtualenv is what Python developers call an isolated environment for development, running, debugging Python code. It is used to isolate a Python interpreter together with a set of libraries and settings. Together with pip, it allows us to develop, deploy and run multiple applications on a single host, each with their own version of the Python interpreter, and separate set of libraries.

Explain *args and **kwargs

Although, there is no formal rule on calling them *args/**kwargs, people tend to name them that way. When a function is declared def my_func(*args, **kwargs), args is a tuple with all positional arguments passed to the function and kwargs is a dict with all keyword arguments. They can be named anything as long as the unpack operators * and ** are used. * unpacks a tuple and ** unpacks a dict.

CheeseShop? What is that?

CheeseShop is what the python developers call PyPI (The Python Package Index) - a repository of software for the Python programming language.

Explain the use of decorators.

Decorators in Python are used to modify or inject code in functions or classes. Using decorators, you can wrap a class or function method call so that a piece of code can be executed before or after the execution of the original code. Decorators can be used to check for permissions, modify or track the arguments passed to a method, logging the calls to a specific method, etc.

What types should you not use for default values?

Do not use mutable objects as default values in the function or method definition. Tuple better

What are the Dunder/Magic/Special methods in Python? Name a few.

Dunder (derived from double underscore) methods are special/magic predefined methods in Python, with names that start and end with a double underscore. There's nothing really magical about them. Examples of these include: __init__ - constructor __str__, __repr__ - object representation (casting to string, printing) __len__, __next__... - generators __enter__, __exit__ - context managers __eq__, __lt__, __gt__ - operator overloading

T/F One blank line following a def line

F No blank line following a def line. Use single blank lines as you judge appropriate within functions or methods.

T/F Two blank lines b/w method def and class to first method?

F One blank line between method definitions and between the class line and the first method.

T/F One blank line b/w top level def. Class / Fun

F Two blank lines between top-level definitions, be they function or class definitions.

T/F Should have whitespace around keyword arguments?

F Yes: def complex(real, imag=0.0): return Magic(r=real, i=imag) Yes: def complex(real, imag: float = 0.0): return Magic(r=real, i=imag) No: def complex(real, imag = 0.0): return Magic(r = real, i = imag) No: def complex(real, imag: float=0.0): return Magic(r = real, i = imag)

T/F Use spaces around paren, brackets, braces.

F Yes: spam(ham[1], {eggs: 2}, []) No: spam( ham[ 1 ], { eggs: 2 }, [ ] )

Cons Lambdas

Harder to read and debug than local functions. The lack of names means stack traces are more difficult to understand. Expressiveness is limited because the function may only contain an expression.

What's a metaclass?

In Python, everything is an object, including classes. And just like any other object, classes are instances of something - a metaclass. The default metaclass is type.

"Is this valid in Python and why? def my_function(): print my_function.what my_function.what = ""right?"" my_function() # Prints ""right?"""

It is valid. In Python, everything is an object, including functions. But if we don't have what defined, we will get an Attribute error.

Pros of lambdas

Lambdas define anonymous functions in an expression, as opposed to a statement. They are often used to define callbacks or operators for higher-order functions like map() and filter().

What are the exceptions to max char limit in Python?

Long import statements.URLs, pathnames, or long flags in comments.Long string module level constants not containing whitespace that would be inconvenient to split across lines such as URLs or pathnames.Pylint disable comments. (e.g.: # pylint: disable=invalid-name)

What's the max line length in Python?

Maximum line length is 80 characters.

What's a Mixin?

Mixin is a concept in Programming in which the class provides functionalities but it is not meant to be used for instantiation. The main purpose of the Mixin is to provide functionalities which are standalone and it would be best if the mixins themselves do not have inheritance with other mixins and also avoid state.

T/F All files should start with shebang - #!/usr/bin/python

Only start the main file of a program with #!/usr/bin/python This line is used by the kernel to find the Python interpreter, but is ignored by Python when importing modules. It is only necessary on a file that will be executed directly.

What is PEP8?

PEP8 is a generally recognized style guide for programming in Python. It covers formatting, comments, naming conventions, but also programming recommendations as well as useful tips on various topics. The main aim of PEP8 is to help developers improve code readability, reliability and maintainability.

What is pickling/unpickling?

Pickling is converting an object to a string representation in python. Generally used for caching and transferring objects between hosts/processes.

What is pip?

Pip is a Python package management system. It provides means of installing, versioning and freezing Python software packages and libraries from the main CheeseShop or third party repositories.

"T/F All empty values are considered falsey in a conditional. 0, [], None, {}, """""

T

T/F Functions must have a docstring

T A function must have a docstring, unless it meets all of the following criteria:not externally visiblevery shortobvious

T/F Use .format and % to format strings?

T And decide when to use +. Yes: x = a + b x = '%s, %s!' % (imperative, expletive) x = '{}, {}'.format(first, second) x = 'name: %s; score: %d' % (name, n) x = 'name: {}; score: {}'.format(name, n) x = f'name: {name}; score: {n}' # Python 3.6+ No: x = '%s%s' % (a, b) # use + in this case x = '{}{}'.format(a, b) # use + in this case x = first + ', ' + second x = 'name: ' + name + '; score: ' + str(n)

T/F Avoid extra parens when possible?

T No: if (x): bar() if not(x): bar() return (foo)

"T/F Should use ""implicit"" false if at possible in conditionals?"

T Yes: if not users: print('no users') if foo == 0: self.handle_zero() if i % 10 == 0: self.handle_multiple_of_ten() def f(x=None): if x is None: x = [] No: if len(users) == 0: print('no users') if foo is not None and not foo: self.handle_zero() if not i % 10: self.handle_multiple_of_ten() def f(x=None): x = x or []

One thing about python OOP is that it doesn't support true private attributes/methods. How do we circumvent this limitation?

There is a convention if we prefix the name with an underscore, it's considered private.

When to use trailing commas?

Trailing commas in sequences of items are recommended only when the closing container token ], ), or } does not appear on the same line as the final element.

T/F Should annotate types in Python3?

Type annotations improve the readability and maintainability of your code. The type checker will convert many runtime errors to build-time errors, and reduce your ability to use Power Features. You are strongly encouraged to enable Python type analysis when updating code. When adding or modifying public APIs, include type annotations and enable checking via pytype in the build system. As static analysis is relatively new to Python, we acknowledge that undesired side-effects (such as wrongly inferred types) may prevent adoption by some projects. In those situations, authors are encouraged to add a comment with a TODO or link to a bug describing the issue(s) currently preventing type annotation adoption in the BUILD file or in the code itself as appropriate.

What imports should you add with Python3?

Use of from __future__ import statements is encouraged. All new code should contain the following and existing code should be updated to be compatible when possible: from __future__ import absolute_import from __future__ import division from __future__ import print_function

Using list comprehension, print the odd numbers between 0 and 100.

[a for a in range(0, 100) if a%2] or [i for i in range(100) if i & 1]

How to print keys from a dict

for key in adict: print(key)

How to reduce an array by summing all elements

from functools import reduce a = [1,2,3] reduce(lambda x, y: x + y, a)


संबंधित स्टडी सेट्स

Property and Casualty-Insurance Law and Regulations

View Set

Power Point #4: Intimidation, Competition, and Sportsmanship

View Set

Ethics in Business TRUE OR FALSE

View Set

Substance-Related and Addictive Disorders

View Set