Skip to main content

Home/ Mac Attack/ Group items tagged classes

Rss Feed Group items tagged

Benjamin Bandt-Horn

Binary Tree in Python - Stack Overflow - 0 views

  • def PreOrder(self): print self.data if self.left: print self.left.PreOrder() if self.right: print self.right.PreOrder()
Benjamin Bandt-Horn

4. More Control Flow Tools - Python v2.7.6 documentation - 0 views

  • *name must occur before **name.
  • keys = sorted(keywords.keys()) for kw in keys: print kw, ":", keywords[kw]
  • Note that the list of keyword argument names is created by sorting the result of the keywords dictionary’s keys() method before printing its contents; if this is not done, the order in which the arguments are printed is undefined
  • ...11 more annotations...
  • They are syntactically restricted to a single expression
  • Like nested function definitions, lambda functions can reference variables from the containing scope
  • Coding Style
  • CamelCase for classes
  • lower_case_with_underscores for functions and methods
  • Always use self as the name for the first method argument
  • comments
  • docstrings
  • separate
  • 79 characters
  • 4-space indentation, and no tabs
  •  
    keys = sorted(keywords.keys()) for kw in keys: print kw, ":", keywords[kw]
Benjamin Bandt-Horn

How to implement __iter__(self) for a container object (Python) - Stack Overflow - 0 views

  • usually __iter__() just return self if you have already define the next() method (generator object)
  • While you are looking at the collections module, consider inheriting from Sequence, Mapping or another abstract base class if that is more appropriate. Here is an example for a Sequence subclass:
  • if hasattr(self.data[0], "__iter__": return self.data[0].__iter__() return self.data.__iter__()
  •  
    if not self.data: raise StopIteration
Benjamin Bandt-Horn

Boilerplate code - Wikipedia, the free encyclopedia - 0 views

  • Or in C# using Automatic Properties with compiler generated backing fields: public class Pet { public PetName Name { get; set; } public Person Owner { get; set; } }
  •  
    Or in C# using Automatic Properties with compiler generated backing fields: public class Pet { public PetName Name { get; set; } public Person Owner { get; set; } }
Benjamin Bandt-Horn

3. Data model - Python v2.6.6 documentation - 0 views

  • it is advised to somehow mix together (e.g. using exclusive or) the hash values for the components of the object that also play a part in comparison of objects.
  • If a class does not define a __cmp__() or __eq__() method it should not define a __hash__() operation either
  • Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.
  • ...2 more annotations...
  • new-style classes
  • By default, instances of both old and new-style classes have a dictionary for attribute storage
  •  
    special method names
Benjamin Bandt-Horn

25.2. doctest - Test interactive Python examples - Python v2.7.6 documentation - 0 views

  • common ways to use doctest: To check that a module’s docstrings are up-to-date by verifying that all interactive examples still work as documented. To perform regression testing by verifying that interactive examples from a test file or a test object work as expected. To write tutorial documentation for a package, liberally illustrated with input-output examples. Depending on whether the examples or the expository text are emphasized, this has the flavor of “literate testing” or “executable documentation”.
  • Running the module as a script causes the examples in the docstrings to get executed and verified
  • The file content is treated as if it were a single giant docstring; the file doesn’t need to contain a Python program! For example, perhaps example.txt contains this
  • ...8 more annotations...
  • You can instruct the Python interpreter to run the doctest module directly from the standard library and pass the file name(s) on the command line:
  • if M.__test__ exists and “is true”, it must be a dict, and each entry maps a (string) name to a function object, class object, or string
  • Which Docstrings Are Examined?
  • Any expected output must immediately follow the final '>>> ' or '... ' line containing the code, and the expected output (if any) extends to the next '>>> ' or all-whitespace line.
  • Execution Context?
  • Directives
  • Whitespace is not allowed between the + or - and the directive option name. The directive option name can be any of the option flag names explained above
  • Unittest
  •  
    Freaking Amazing.
Benjamin Bandt-Horn

Elegant ways to support equivalence ("equality") in Python classes - Stack Overflow - 0 views

  • mixin class
  • Another issue with the __dict__ comparison is what if you have an attribute that you don't want to consider in your definition of equality (say for example a unique object id, or metadata like a time created stamp).
  • isinstance sucks
  • ...4 more annotations...
  • if type(other) is type(self):
  • Check types more strictly, like this:
  • is tests for object identity. This means a is b will be True in the case when a and b both hold the reference to the same object
  • __cmp__ was removed from python 3 so avoid it
  •  
    mixin class
Benjamin Bandt-Horn

Python : map and filter vs for loops - 0 views

  • Re: Python : map and filter vs for loops The underlying implementation of map and filter are different than loops, even though they accomplish the same thing. Which idiom runs fastest can change from version to version. Right now I think list comprehensions are the fastest. So instead of Code: filter(f, range(2,25)), the list comprehension would be Code: [x for x in range(2,25) if f(x)] and instead of Code: map(cube, range(1, 11)) the list comprehension would be Code: [cube(x) for x in range(1,11)]
  •  
    Python : map and filter vs for loops The underlying implementation of map and filter are different than loops, even though they accomplish the same thing. Which idiom runs fastest can change from version to version. Right now I think list comprehensions are the fastest.
Benjamin Bandt-Horn

gevent: A coroutine-based network library for Python - 0 views

  • gevent is a coroutine-based Python networking library that uses greenlet to provide a high-level synchronous API on top of the libev event loop. Features include: Fast event loop based on libev (epoll on Linux, kqueue on FreeBSD). Lightweight execution units based on greenlet. API that re-uses concepts from the Python standard library (for example there are Events and Queues). Cooperative sockets with SSL support » DNS queries performed through threadpool or c-ares. Monkey patching utility to get 3rd party modules to become cooperative »
  •  
    gevent is a coroutine-based Python networking library that uses greenlet to provide a high-level synchronous API on top of the libev event loop. Features include: Fast event loop based on libev (epoll on Linux, kqueue on FreeBSD). Lightweight execution units based on greenlet. API that re-uses concepts from the Python standard library (for example there are Events and Queues). Cooperative sockets with SSL support » DNS queries performed through threadpool or c-ares. Monkey patching utility to get 3rd party modules to become cooperative »
Benjamin Bandt-Horn

IntegratingPythonWithOtherLanguages - Python Wiki - 0 views

  • ActiveState research Python for .NET is a near-seamless integration of the CPython runtime with the .NET Common Language Runtime (CLR). IronPython is an implementation of Python for .net, which allows you to import .net class libraries seamlessly in Python.
Benjamin Bandt-Horn

Binary Search Tree library in Python | Laurent Luce's Blog - 0 views

  • This article is about a Python library I created to manage binary search trees. I will go over the following: Node class Insert method Lookup method Delete method Print method Comparing 2 trees Generator returning the tree elements one by one
  • https://laurentluce@github.com/laurentluce/python-algorithms.git
  • binary search tree
  • ...5 more annotations...
  • Delete method
  • There are 3 possibilities to handle: 1- The node to remove has no child. 2- The node to remove has 1 child. 3- The node to remove has 2 children.
  • look for its successor by going right then left until we reach a leaf
  • if node is None:
  • ‘A’ < ‘B’ is True in Python.
  •  
    This article is about a Python library I created to manage binary search trees. I will go over the following: Node class Insert method Lookup method Delete method Print method Comparing 2 trees Generator returning the tree elements one by one
Benjamin Bandt-Horn

GuiceBasics - snake-guice - Basic concepts behind the Guice methodology - A simple, lig... - 0 views

  • The Dependency Injection (DI) is an essential pattern when building large systems. It forces classes to be more modular and reusable by making them depend on an interface instead of a concrete class. Simply put classes favor instances passed into the init instead of creating new instances.
  •  
    The Dependency Injection (DI) is an essential pattern when building large systems. It forces classes to be more modular and reusable by making them depend on an interface instead of a concrete class. Simply put classes favor instances passed into the init instead of creating new instances.
Benjamin Bandt-Horn

Classes & Iterators - Dive Into Python 3 - 0 views

  • Comprehensions are just a simple form of iterators. Generators are just a simple form of iterators
  • The first argument of every class method, including the __init__() method, is always a reference to the current instance of the class. By convention, this argument is named self.
  • self is not a reserved word in Python, merely a naming convention
  • ...6 more annotations...
  • To build an iterator from scratch, Fib needs to be a class, not a function.
  • in most cases), __iter__() simply returns self, since this class implements its own __next__() method.
  • a for loop will call this automatically, but you can also call it yourself manually
  • the __next__() method raises a StopIteration exception, this signals to the caller that the iteration is exhausted. Unlike most exceptions, this is not an error; it’s a normal condition that just means that the iterator has no more values to generate. If the caller is a for loop, it will notice this StopIteration exception and gracefully exit the loop. (In other words, it will swallow the exception.)
  • Do not use yield here; that’s a bit of syntactic sugar that only applies when you’re using generators. Here you’re creating your own iterator from scratch; use return instead
  • raise StopIteration
  •  
    Comprehensions are just a simple form of iterators. Generators are just a simple form of iterators
Benjamin Bandt-Horn

BitwiseOperators - Python Wiki - 0 views

  • x << yReturns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.
  • x >> yReturns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y.
  • x & yDoes a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0.
  • ...5 more annotations...
  • x ^ yDoes a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x if that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1.
  • x | yDoes a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0, otherwise it's 1.
  • ~ x Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1. This is the same as -x - 1.
  • Just remember about that infinite series of 1 bits in a negative number, and these should all make sense.
  • One more point: Python allows operator overloading, so some classes may be written to allow the bitwise operators, but with some other meaning. For instance, the new sets module for Python 2.3 uses | and & for union and intersection.
  •  
    The Operators: x << y Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.
Benjamin Bandt-Horn

Ternary conditional operator in Python - Stack Overflow - 0 views

  •  
    Yes, it was added in version 2.5. It's frowned upon by some pythonistas, so keep that in mind. The syntax is: a if test else b First test is evaluated, then either a or b is returned based on the Boolean value of test; if test evaluates to True a is returned, else b is returned. For example: >>> 'true' if True else 'false' 'true' >>> 'true' if False else 'false' 'false'
Benjamin Bandt-Horn

Practical guidelines for beautiful Python code | TurnKey Linux Blog - 0 views

  • a well defined mental model of the problem domain
  • Refining the architecture is part of the "refactor mercilessly" rule
  • If you've never inherited from a built-in data type, experiment with a small test case in a throw away script. This way you don't mangle your current project and you can be as experimental as you like.
  • ...3 more annotations...
  • constants are always class level attributes because they are shared by all instances
  • code is communication
  • If a method doesn't need access to instance level attributes then it should be a class method, not a regular method. If a method doesn't need access to class level attributes then it should be a static method, not a class method.
Benjamin Bandt-Horn

python - if A vs if A is not None: - Stack Overflow - 0 views

  •  
    The statement if A: will call A.__nonzero__()
Benjamin Bandt-Horn

Fox toolkit - Wikipedia, the free encyclopedia - 0 views

  • The FOX toolkit is an open source, cross-platform widget toolkit, that is, a library of basic elements for building a graphical user interface (GUI). FOX stands for Free Objects for X.
  • FOX differentiates itself in the following way from other cross-platform toolkits: Tk is a cross-platform toolkit but does not have all of the widgets that FOX considers desirable. Qt had a different licensing model, which might have required a commercial license in some cases where FOX would not. (This is no longer the case starting with Qt 4.5.) wxWidgets promotes the use of native widgets on each supported platform. FLTK is a fast, low-footprint library that supports rapid application development, and requires less code to use, but lacks advanced widgets. All of these toolkits have some support for programming natively on Mac OS and/or Mac OS X platforms, which FOX currently does not support[
  •  
    The FOX toolkit is an open source, cross-platform widget toolkit, that is, a library of basic elements for building a graphical user interface (GUI). FOX stands for Free Objects for X.
Benjamin Bandt-Horn

Chapter 1. python 2.0 - 1.55.0 - 0 views

  • The Boost Python Library is a framework for interfacing Python and C++. It allows you to quickly and seamlessly expose C++ classes functions and objects to Python, and vice-versa, using no special tools -- just your C++ compiler. It is designed to wrap C++ interfaces non-intrusively, so that you should not have to change the C++ code at all in order to wrap it, making Boost.Python ideal for exposing 3rd-party libraries to Python. The library's use of advanced metaprogramming techniques simplifies its syntax for users, so that wrapping code takes on the look of a kind of declarative interface definition language (IDL).
  •  
    The Boost Python Library is a framework for interfacing Python and C++. It allows you to quickly and seamlessly expose C++ classes functions and objects to Python, and vice-versa, using no special tools -- just your C++ compiler. It is designed to wrap C++ interfaces non-intrusively, so that you should not have to change the C++ code at all in order to wrap it, making Boost.Python ideal for exposing 3rd-party libraries to Python. The library's use of advanced metaprogramming techniques simplifies its syntax for users, so that wrapping code takes on the look of a kind of declarative interface definition language (IDL).
Benjamin Bandt-Horn

17.1 subprocess -- Subprocess management - 0 views

  • The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several other, older modules and functions, such as: os.system os.spawn* os.popen* popen2.* commands.*
  •  
    The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several other, older modules and functions, such as: os.system os.spawn* os.popen* popen2.* commands.*
1 - 20 of 29 Next ›
Showing 20 items per page