Difference between revisions of "Python:Various"
KevinYager (talk | contribs) |
KevinYager (talk | contribs) (→Super) |
||
| Line 17: | Line 17: | ||
</source> | </source> | ||
| + | Also note that you can exploit * and ** to pass arguments along: | ||
| + | <source lang="python" line > | ||
| + | #!/usr/bin/python | ||
| + | class Foo(object): | ||
| + | def __init__(self, value1, value2): | ||
| + | # do something with the values | ||
| + | print value1, value2 | ||
| + | |||
| + | class MyFoo(Foo): | ||
| + | def __init__(self, *args, **kwargs): | ||
| + | # do something else, don't care about the args | ||
| + | print 'myfoo' | ||
| + | super(MyFoo, self).__init__(*args, **kwargs) | ||
| + | </source> | ||
==Matrix== | ==Matrix== | ||
Revision as of 16:21, 14 January 2015
This page collects some notes/hints about the use of the Python programming language.
Super
In object-oriented programming, one must sometimes call upon the parent class or super class.
In python, a given object (self) can refer to its parent as:
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Cube(Platonic):
def __init__(self, args={}):
super(Cube, self).__init__( args=args )
Also note that you can exploit * and ** to pass arguments along:
#!/usr/bin/python
class Foo(object):
def __init__(self, value1, value2):
# do something with the values
print value1, value2
class MyFoo(Foo):
def __init__(self, *args, **kwargs):
# do something else, don't care about the args
print 'myfoo'
super(MyFoo, self).__init__(*args, **kwargs)
Matrix
Multiply matrix/array/grid by vector
#!/usr/bin/python import numpy as np # 2D example size = 11 extent = 1.0 #axis_x = np.linspace( -extent, +extent, size ) #axis_y = np.linspace( -extent, +extent, size ) X, Y = np.meshgrid( axis_x, axis_y ) # Example 2D arrays v = np.asarray( [ np.linspace( 0, 1, size ) ] ) print X*v # Multiplies across row (x-direction) print X*v.transpose() # Multiplies down columns (y-direction) # 3D example size = 3 extent = 1.0 X, Y, Z = np.mgrid[ -extent:+extent:size*1j , -extent:+extent:size*1j , -extent:+extent:size*1j ] # Example 3D arrays # Example vectors we want to multiply with u = np.linspace( 1, 2, size ).reshape(size,1,1) # Multiplies down layers (z-direction) v = np.linspace( 1, 2, size ).reshape(1,size,1) # Multiplies down column (y-direction) w = np.linspace( 1, 2, size ).reshape(1,1,size) # Multiplies across row (x-direction) print X print '--' print u print X*u print '--' print v print X*v print '--' print w print X*w