Python Advanced Intro #02 | Object-Oriented Programming

Contents

  1. OOP in GhPython
    1. Realtime update | example
    2. Inheritance
  2. Practice
    1. Cluster of Random Walkers | example

OOP in GhPython

Realtime update

import ghpythonlib.components as gh
import rhinoscriptsyntax as rs
import Rhino.Geometry as rg
import random as rand

class RandomWalker:

 def __init__(self, step):
  self.pos = rg.Point3d(0,0,0)
  self.step = step

 def walk(self):
  sph = gh.Sphere(gh.XYPlane([0,0,0]),self.step)
  randVec = gh.PopulateGeometry(sph, 1, rand.randint(0,100))
  self.pos = rs.VectorAdd(self.pos,randVec)

a = RandomWalker(x)

Practice

Cluster of Random Walkers

import ghpythonlib.components as gh
import random as rand

class agent:
    def __init__(self, pos, step):
        self.pos = pos
        self.step = step
 
    def walk(self):
        sph = gh.Sphere(gh.XYPlane([0,0,0]),self.step)
        randVec = gh.PopulateGeometry(sph, 1, rand.randint(0,100))
        self.pos = gh.Addition(self.pos,randVec)

class cluster:
    def __init__(self,pts):
        self.agents = []
        for pt in pts:
            a = agent(pt,5)
            self.agents.append(a)
    
    def update(self):
        for agent in self.agents:
            agent.walk()
    
    def positions(self):
        pos = []
        for agent in self.agents:
            pos.append(agent.pos)
        return pos

a = cluster(x)