Skip to content

Instantly share code, notes, and snippets.

@marius92mc
Last active May 7, 2017 19:52
Show Gist options
  • Save marius92mc/be7c4b777ccce676592c0c5b9a24fbff to your computer and use it in GitHub Desktop.
Save marius92mc/be7c4b777ccce676592c0c5b9a24fbff to your computer and use it in GitHub Desktop.
# $ grep -nre "#include" *.cpp | wc -l
# Files I/O
"""
Some objects define standard clean-up actions to be undertaken when
the object is no longer needed, regardless of whether or not the
operation using the object succeeded or failed. Look at the following
example, which tries to open a file and print its contents to the screen.
"""
# Not recommended
for line in open("myfile.txt"):
print(line, end="")
"""
The problem with this code is that it leaves the file open for an
indeterminate amount of time after this part of the code
has finished executing.
This is not an issue in simple scripts,
but can be a problem for larger applications.
The `with` statement allows objects like files to be used in
a way that ensures they are always cleaned up promptly and correctly.
"""
# Recommended
with open("myfile.txt") as f:
for line in f:
print(line, end="")
"""
After the statement is executed, the file f is always closed,
even if a problem was encountered while processing the lines.
Objects which, like files, provide predefined clean-up actions
will indicate this in their documentation.
"""
# Set
my_set = ()
my_set.add(2)
my_set.add(3)
print(1 in my_set) # False
print(2 in my_set) # True
# Dictionaries
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
for name, phone in table.items():
print("{0:10} ==> {1:10}".format(name, phone))
# ^ the index of the parameter from the format() function parameters
# ^ how much space to reserve for that printed content
"""
Jack ==> 4098
Sjoerd ==> 4127
Dcab ==> 7678
"""
# OOP
"""
A Word About Names and Objects
Objects have individuality, and multiple names (in multiple scopes) can be
bound to the same object. This is known as aliasing in other languages.
This is usually not appreciated on a first glance at Python, and can be
safely ignored when dealing with immutable basic types (numbers, strings, tuples).
However, aliasing has a possibly surprising effect on the semantics of Python
code involving mutable objects such as lists, dictionaries, and most other types.
This is usually used to the benefit of the program, since aliases behave
like pointers in some respects.
For example, passing an object is cheap since only a pointer is
passed by the implementation; and if a function modifies an object
passed as an argument, the caller will see the change — this eliminates the need
for two different argument passing mechanisms as in Pascal.
"""
class Dog:
kind = 'canine' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind # shared by all dogs
'canine'
>>> e.kind # shared by all dogs
'canine'
>>> d.name # unique to d
'Fido'
>>> e.name # unique to e
'Buddy'
class Dog:
# WRONG
# tricks = [] # mistaken use of a class variable,
# unexpectedly shared by all dogs and we don't want that for this case
def __init__(self, name):
self.name = name
self.tricks = [] # creates a new empty list for each dog
def add_trick(self, trick):
self.tricks.append(trick)
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks
['roll over']
>>> e.tricks
['play dead']
class Bag:
def __init__(self):
self.data = [] # creates an empty list, unique for each instance of the class
def add(self, x):
self.data.append(x)
def addtwice(self, x):
self.add(x)
self.add(x)
# Inheritance
class DerivedClassName(BaseClassName):
<statement-1>
.
.
.
<statement-N>
class DerivedClassName(modname.BaseClassName):
pass
"""
Derived classes may override methods of their base classes.
Because methods have no special privileges when calling other methods of
the same object, a method of a base class that calls another method defined
in the same base class may end up calling a method of a derived class that overrides it.
(For C++ programmers: all methods in Python are effectively virtual.)
An overriding method in a derived class may in fact want to extend rather
than simply replace the base class method of the same name.
There is a simple way to call the base class method directly: just
call BaseClassName.methodname(self, arguments).
This is occasionally useful to clients as well.
(Note that this only works if the base class is accessible as BaseClassName in the global scope.)
Python has two built-in functions that work with inheritance:
Use isinstance() to check an instance’s type:
isinstance(obj, int) will be True only if obj.__class__ is int or some class derived from int.
Use issubclass() to check class inheritance:
issubclass(bool, int) is True since bool is a subclass of int.
However,
issubclass(float, int) is False since float is not a subclass of int.
"""
"""
Managing packages with pip inside virtualenv
https://docs.python.org/3/tutorial/venv.html#managing-packages-with-pip
Inside virtualenv, of course
$ pip search astronomy
$ pip install novas
$ pip install requests==2.6.0
$ pip install --upgrade requests # upgrade the requests package to the latest version
$ pip show requests # will display information about the requests package
$ pip uninstall requests # followed by one or more package names will remove the packages from the virtual environment
$ pip list # will display all of the packages installed in the virtual environment
$ pip freeze > requirements.txt
$ pip install -r requirements.txt
"""
"""
virtualenv
http://python-guide-pt-br.readthedocs.io/en/latest/dev/virtualenvs/
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment