Date objects can be created using the datetime.date() method. This method takes year, month and day parameters.
import datetime # Create 7th Feb 2011 d = datetime.date(2011,2,7) assert str(d) == '2011-02-07'
Date objects can be created using the datetime.date() method. This method takes year, month and day parameters.
import datetime # Create 7th Feb 2011 d = datetime.date(2011,2,7) assert str(d) == '2011-02-07'
Python does not have any syntax for creating enums (it’s proposal was rejected), but there are some alternatives.
1. Using a class
class Numbers(object): ONE = 1 TWO = 2 THREE = 3 assert Numbers.ONE == 1 assert Numbers.TWO == 2 assert Numbers.THREE == 3
2. Use a function that dynamically creates a new class
def enum(**enums): return type('Enum', (object,), enums) Numbers = enum(ONE=1, TWO=2, THREE=3) assert Numbers.ONE == 1 assert Numbers.TWO == 2 assert Numbers.THREE == 3
3. Create a new object that extends Python’s set
class Enum(set): def __getattr__(self, name): if name in self: return name raise AttributeError Numbers = Enum( "ONE TWO THREE".split() ) error = False try: print Numbers.ONE print Numbers.TWO print Numbers.THREE except: error = True assert error == False try: print Numbers.FOUR except: error = True assert error == True
We can check if a variable is defined in Python using a try/except.
try: print x except NameError: x = 0 assert x == 0
A lambda function is essentially a function that has no name. They are often used as parameters to other functions.
A simple lambda function to square numbers may be created as follows:
# Create a lambda function that takes one parameter and returns it's square # and assign to the variable f f = lambda x: x*x assert f(2) == 4 assert f(3) == 9
We can also pass lambda functions as function parameters without assigning to to intermediate variables.
# Create a function that takes a function and a list, then applies the function to each element of the list def map(f, list): for i in range(0,len(list)): list[i] = f(list[i]) # Create a simple test list list = [1,2,3] # Call our map function passing in a lambda square function and the test list map( lambda x: x*x, list ) assert list[0] == 1 assert list[1] == 4 assert list[2] == 9
Note that lambda functions do not include a return statement.
You can use a for in loop to get the elements of the array.
colours = ["red","green","blue"] for colour in colours: print colour # red # green # blue
However if you also need access to the position of the element in the array we can use a for in loop over a range
colours = ["red","green","blue"] for i in range(0, len(colours)): print i, colour[i] # 0 red # 1 green # 2 blue
Python has a type() function that is used to provide the type of an object, but this same function can be used to dynamically create classes at runtime.
For example, suppose we have the following class:
class Foo(object): x = 10 y = 20 def get_x(self): return self.x def get_y(self): return self.y
We can create an identical class using the type() function.
Bar = type( 'Bar', (object,), dict( x = 10, y = 20, get_x=lambda self:self.x, get_y=lambda self:self.y ) )
And testing these are the equivalent.
f = Foo() b = Bar() assert f.x == b.x == 10 assert f.y == b.y == 20 assert f.get_x() == b.get_x() == 10 assert f.get_y() == b.get_y() == 20
For more information see:
http://docs.python.org/library/functions.html#type
Python does not have any particular language construct for declaring constants, so they are typically declared as just variables names with all capital letters.
NEW_POST = 1 ARCHIVED_POST = 2 DELETED_POST = 3
Alternatively they may be declared as class variables.
class Post(object): NEW = 1 ARCHIVED = 2 DELETED = 3 assert Post.NEW == 1 assert Post.ARCHIVED == 2 assert Post.DELETED == 3
The simplest class is something like:
class Foo(object): pass
This can be initialised with an __init__() method
class Foo(object): def __init__(self): self.name = None
We can then add additional methods
class Foo(object): def __init__(self): self.name = None def set_name(self, name): self.name = name def get_name(self): return self.name
This class is then used as follows
o = Foo() o.set_name("Hello") assert o.get_name() == "Hello"
We can then implement simple inheritance
class Bar(Foo): pass
Add a constructor
class Bar(Foo): def __init__(self): self.set_name("World")
This object is then used as follows
o = Bar() assert o.get_name() == "World"
Python does not support a switch statement, but instead prefers an if/elif/else statement.
x = 5 value = 0 if x < 5: value = -1 elif x > 5: value = 1 else: value = 0 assert value == 0
A proposal to include a switch statement in the language has been rejected.
Python provides a json library that enables JSON encoding of data.
import json data = dict( first = "Foo", last = "Bar", ) assert json.dumps(data) == '{"last": "Bar", "first": "Foo"}'
For more information see
http://docs.python.org/library/json.html