In [1]:
a = 1
help(a)


Help on int object:

class int(object)
 |  int(x=0) -> integer
 |  int(x, base=10) -> integer
 |  
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is a number, return x.__int__().  For floating point
 |  numbers, this truncates towards zero.
 |  
 |  If x is not a number or if base is given, then x must be a string,
 |  bytes, or bytearray instance representing an integer literal in the
 |  given base.  The literal can be preceded by '+' or '-' and be surrounded
 |  by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
 |  Base 0 means to interpret the base from the string as an integer literal.
 |  >>> int('0b100', base=0)
 |  4
 |  
 |  Methods defined here:
 |  
 |  __abs__(self, /)
 |      abs(self)
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __and__(self, value, /)
 |      Return self&value.
 |  
 |  __bool__(self, /)
 |      self != 0
 |  
 |  __ceil__(...)
 |      Ceiling of an Integral returns itself.
 |  
 |  __divmod__(self, value, /)
 |      Return divmod(self, value).
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __float__(self, /)
 |      float(self)
 |  
 |  __floor__(...)
 |      Flooring an Integral returns itself.
 |  
 |  __floordiv__(self, value, /)
 |      Return self//value.
 |  
 |  __format__(...)
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getnewargs__(...)
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __index__(self, /)
 |      Return self converted to an integer, if self is suitable for use as an index into a list.
 |  
 |  __int__(self, /)
 |      int(self)
 |  
 |  __invert__(self, /)
 |      ~self
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __lshift__(self, value, /)
 |      Return self<<value.
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mod__(self, value, /)
 |      Return self%value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __neg__(self, /)
 |      -self
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __or__(self, value, /)
 |      Return self|value.
 |  
 |  __pos__(self, /)
 |      +self
 |  
 |  __pow__(self, value, mod=None, /)
 |      Return pow(self, value, mod).
 |  
 |  __radd__(self, value, /)
 |      Return value+self.
 |  
 |  __rand__(self, value, /)
 |      Return value&self.
 |  
 |  __rdivmod__(self, value, /)
 |      Return divmod(value, self).
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __rfloordiv__(self, value, /)
 |      Return value//self.
 |  
 |  __rlshift__(self, value, /)
 |      Return value<<self.
 |  
 |  __rmod__(self, value, /)
 |      Return value%self.
 |  
 |  __rmul__(self, value, /)
 |      Return value*self.
 |  
 |  __ror__(self, value, /)
 |      Return value|self.
 |  
 |  __round__(...)
 |      Rounding an Integral returns itself.
 |      Rounding with an ndigits argument also returns an integer.
 |  
 |  __rpow__(self, value, mod=None, /)
 |      Return pow(value, self, mod).
 |  
 |  __rrshift__(self, value, /)
 |      Return value>>self.
 |  
 |  __rshift__(self, value, /)
 |      Return self>>value.
 |  
 |  __rsub__(self, value, /)
 |      Return value-self.
 |  
 |  __rtruediv__(self, value, /)
 |      Return value/self.
 |  
 |  __rxor__(self, value, /)
 |      Return value^self.
 |  
 |  __sizeof__(...)
 |      Returns size in memory, in bytes
 |  
 |  __str__(self, /)
 |      Return str(self).
 |  
 |  __sub__(self, value, /)
 |      Return self-value.
 |  
 |  __truediv__(self, value, /)
 |      Return self/value.
 |  
 |  __trunc__(...)
 |      Truncating an Integral returns itself.
 |  
 |  __xor__(self, value, /)
 |      Return self^value.
 |  
 |  bit_length(...)
 |      int.bit_length() -> int
 |      
 |      Number of bits necessary to represent self in binary.
 |      >>> bin(37)
 |      '0b100101'
 |      >>> (37).bit_length()
 |      6
 |  
 |  conjugate(...)
 |      Returns self, the complex conjugate of any int.
 |  
 |  from_bytes(...) from builtins.type
 |      int.from_bytes(bytes, byteorder, *, signed=False) -> int
 |      
 |      Return the integer represented by the given array of bytes.
 |      
 |      The bytes argument must either support the buffer protocol or be an
 |      iterable object producing bytes.  Bytes and bytearray are examples of
 |      built-in objects that support the buffer protocol.
 |      
 |      The byteorder argument determines the byte order used to represent the
 |      integer.  If byteorder is 'big', the most significant byte is at the
 |      beginning of the byte array.  If byteorder is 'little', the most
 |      significant byte is at the end of the byte array.  To request the native
 |      byte order of the host system, use `sys.byteorder' as the byte order value.
 |      
 |      The signed keyword-only argument indicates whether two's complement is
 |      used to represent the integer.
 |  
 |  to_bytes(...)
 |      int.to_bytes(length, byteorder, *, signed=False) -> bytes
 |      
 |      Return an array of bytes representing an integer.
 |      
 |      The integer is represented using length bytes.  An OverflowError is
 |      raised if the integer is not representable with the given number of
 |      bytes.
 |      
 |      The byteorder argument determines the byte order used to represent the
 |      integer.  If byteorder is 'big', the most significant byte is at the
 |      beginning of the byte array.  If byteorder is 'little', the most
 |      significant byte is at the end of the byte array.  To request the native
 |      byte order of the host system, use `sys.byteorder' as the byte order value.
 |      
 |      The signed keyword-only argument determines whether two's complement is
 |      used to represent the integer.  If signed is False and a negative integer
 |      is given, an OverflowError is raised.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  denominator
 |      the denominator of a rational number in lowest terms
 |  
 |  imag
 |      the imaginary part of a complex number
 |  
 |  numerator
 |      the numerator of a rational number in lowest terms
 |  
 |  real
 |      the real part of a complex number


In [2]:
a = 1
dir(a)


Out[2]:
['__abs__',
 '__add__',
 '__and__',
 '__bool__',
 '__ceil__',
 '__class__',
 '__delattr__',
 '__dir__',
 '__divmod__',
 '__doc__',
 '__eq__',
 '__float__',
 '__floor__',
 '__floordiv__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__index__',
 '__init__',
 '__int__',
 '__invert__',
 '__le__',
 '__lshift__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__neg__',
 '__new__',
 '__or__',
 '__pos__',
 '__pow__',
 '__radd__',
 '__rand__',
 '__rdivmod__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rfloordiv__',
 '__rlshift__',
 '__rmod__',
 '__rmul__',
 '__ror__',
 '__round__',
 '__rpow__',
 '__rrshift__',
 '__rshift__',
 '__rsub__',
 '__rtruediv__',
 '__rxor__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__sub__',
 '__subclasshook__',
 '__truediv__',
 '__trunc__',
 '__xor__',
 'bit_length',
 'conjugate',
 'denominator',
 'from_bytes',
 'imag',
 'numerator',
 'real',
 'to_bytes']

In [3]:
a = 1
a.__abs__()


Out[3]:
1

In [4]:
b = -2
b.__abs__()


Out[4]:
2

In [5]:
a = 1
abs(a)


Out[5]:
1

In [6]:
b = -2
abs(b)


Out[6]:
2

In [7]:
import math
dir(math.sin)


Out[7]:
['__call__',
 '__class__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__le__',
 '__lt__',
 '__module__',
 '__name__',
 '__ne__',
 '__new__',
 '__qualname__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__self__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__text_signature__']

In [8]:
import math 
math.sin.__doc__


Out[8]:
'sin(x)\n\nReturn the sine of x (measured in radians).'

In [9]:
class Particle(object):
    """A particle is a constituent unit of the universe."""
    # class body definition here

In [10]:
# particle.py
class Particle(object):
    """A particle is a constituent unit of the universe."""
    roar = "I am a particle!"

In [11]:
import os
import sys
sys.path.insert(0, os.path.abspath('obj'))

In [12]:
# import the particle module
import particle as p
print(p.Particle.roar)


I am a particle!

In [13]:
# import the particle module
import particle as p
higgs = p.Particle()
print(higgs.roar)


I am a particle!

In [14]:
# import the Particle class from the particle module
from particle import Particle

# create an empty list to hold observed particle data
obs = []

# append the first particle
obs.append(Particle())

# assign its position
obs[0].r = {'x': 100.0, 'y': 38.0, 'z': -42.0}

# append the second particle
obs.append(Particle())

# assign the position of the second particle
obs[1].r = {'x': 0.01, 'y': 99.0, 'z': 32.0}

# print the positions of each particle
print(obs[0].r)
print(obs[1].r)


{'x': 100.0, 'z': -42.0, 'y': 38.0}
{'x': 0.01, 'z': 32.0, 'y': 99.0}

In [15]:
# particle.py
class Particle(object):
    """A particle is a constituent unit of the universe.
    
    Attributes
    ----------
    c : charge in units of [e]
    m : mass in units of [kg]
    r : position in units of [meters]
    """

    roar = "I am a particle!"

    def __init__(self):
        """Initializes the particle with default values for 
        charge c, mass m, and position r.
        """
        self.c = 0
        self.m = 0
        self.r = {'x': 0, 'y': 0, 'z': 0}

In [16]:
# particle.py
class Particle(object):
    """A particle is a constituent unit of the universe.
    
    Attributes
    ----------
    c : charge in units of [e]
    m : mass in units of [kg]
    r : position in units of [meters]
    """

    roar = "I am a particle!"

    def __init__(self, charge, mass, position):
        """Initializes the particle with supplied values for 
        charge c, mass m, and position r.
        """
        self.c = charge
        self.m = mass
        self.r = position

In [17]:
# particle.py
class Particle(object):
    """A particle is a constituent unit of the universe.
    
    Attributes
    ----------
    c : charge in units of [e]
    m : mass in units of [kg]
    r : position in units of [meters]
    """

    roar = "I am a particle!"

    def __init__(self, charge, mass, position): 
        """Initializes the particle with supplied values for 
        charge c, mass m, and position r.
        """
        self.c = charge
        self.m = mass
        self.r = position

    def hear_me(self):
        myroar = self.roar + (
            "  My charge is:     " + str(self.c) + 
            "  My mass is:       " + str(self.m) +
            "  My x position is: " + str(self.r['x']) +
            "  My y position is: " + str(self.r['y']) +
            "  My z position is: " + str(self.r['z']))
        print(myroar)

In [18]:
from scipy import constants

import particle as p

m_p = constants.m_p
r_p = {'x': 1, 'y': 1, 'z': 53}
a_p = p.Particle(1, m_p, r_p)
a_p.hear_me()


I am a particle!
 My mass is: 1.672621777e-27
 My charge is: 1
 My x position is: 1
 My y position is: 1
 My z position is: 53

In [19]:
def flip(self):
    if self.flavor == "up":
        self.flavor = "down"
    elif self.flavor == "down":
        self.flavor = "up"
    elif self.flavor == "top":
        self.flavor = "bottom"
    elif self.flavor == "bottom":
        self.flavor = "top"
    elif self.flavor == "strange":
        self.flavor = "charm"
    elif self.flavor == "charm":
        self.flavor = "strange"
    else :
        raise AttributeError("The quark cannot be flipped, because the "
                             "flavor is not valid.")

In [20]:
# import the class
from quark import Quark

# create a Quark object
t = Quark()

# set the flavor
t.flavor = "top"

# flip the flavor
t.flip()

# print the flavor
print(t.flavor)


bottom

In [21]:
from scipy import constants

class Particle(object):
    """A particle is a constituent unit of the universe."""

    # ... other parts of the class definition ...

    def delta_x_min(self, delta_p_x):
        hbar = constants.hbar
        delx_min = hbar / (2.0 * delta_p_x)
        return delx_min

In [22]:
def possible_flavors():
    return ["up", "down", "top", "bottom", "strange", "charm"]

In [23]:
from scipy import constants

def possible_flavors():
  return["up","down","top","bottom","strange","charm"]

class Particle(object):
    """A particle is a constituent unit of the universe."""

    # ... other parts of the class definition ...

    def delta_x_min(self, delta_p_x):
        hbar = constants.hbar
        delx_min = hbar / (2.0 * delta_p_x)
        return delx_min

    @staticmethod
    def possible_flavors():
        return ["up", "down", "top", "bottom", "strange", "charm"]

In [24]:
def total_charge(particles):
    tot = 0
    for p in particles:
        tot += p.c
    return tot

In [25]:
def total_charge(collection):
    tot = 0
    for p in collection:
        if isinstance(p, Particle):
            tot += p.c
    return tot

In [26]:
# elementary.py
class ElementaryParticle(Particle):

    def __init__(self, spin):
        self.s = spin
        self.is_fermion = bool(spin % 1.0)
        self.is_boson = not self.is_fermion

In [27]:
# composite.py
class CompositeParticle(Particle):

    def __init__(self, parts):
        self.constituents = parts

In [28]:
# elementary.py
class ElementaryParticle(Particle):

    roar = "I am an Elementary Particle!"

    def __init__(self, spin):
        self.s = spin
        self.is_fermion = bool(spin % 1.0)
        self.is_boson = not self.is_fermion

In [29]:
from elementary import ElementaryParticle

spin = 1.5
p = ElementaryParticle(spin)
p.s
p.hear_me()


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-29-04a38822c38e> in <module>()
      4 p = ElementaryParticle(spin)
      5 p.s
----> 6 p.hear_me()

/home/scopatz/physics-codes-examples/obj/particle.py in hear_me(self)
     13         " My x position is: " + str(self.r['x']) +"\n"+\
     14         " My y position is: " + str(self.r['y']) +"\n"+\
---> 15         " My z position is: " + str(self.r['z'])
     16         print(self.myroar)
     17 

AttributeError: 'ElementaryParticle' object has no attribute 'm'

In [30]:
import randphys as rp

class Quark(ElementaryParticle):

    def __init__(self):
        phys = rp.RandomPhysics()
        self.color = phys.color()
        self.charge = phys.charge()
        self.color_charge = phys.color_charge()
        self.spin = phys.spin()
        self.flavor = phys.flavor()

In [31]:
def add_is_particle(cls): <1>
    cls.is_particle = True <2>
    return cls <3>


@add_is_particle <4>
class Particle(object):
    """A particle is a constituent unit of the universe."""

    # ... other parts of the class definition ...


  File "<ipython-input-31-7baafc632b38>", line 1
    def add_is_particle(cls): <1>
                              ^
SyntaxError: invalid syntax

In [32]:
from math import sqrt

def add_distance(cls):
    def distance(self, other): 
        d2 = 0.0
        for axis in ['x', 'y', 'z']:
            d2 += (self.r[axis] - other.r[axis])**2
        d = sqrt(d2)
        return d
    cls.distance = distance
    return cls 


@add_distance
class Particle(object):
    """A particle is a constituent unit of the universe."""

    # ... other parts of the class definition ...

In [33]:
type(type)


Out[33]:
type

In [34]:
class IsParticle(type):
    pass

In [35]:
class Particle(metaclass=IsParticle):
    """A particle is a constituent unit of the universe."""

    # ... other parts of the class definition ...

In [36]:
isinstance(Particle, IsParticle)
p = Particle()

In [37]:
isinstance(p, IsParticle)


Out[37]:
False