Johan
Johan

Reputation: 1557

Python dynamic methods

I'm trying to rewrite some javascript code into Python. Which brings some problems since I'm quite new to python but it's a good excercise I reckon.

Anyway, the problem at hand is that I need dynamic methods in an object that are defined somewhere else... (I know how this sounds, but bear with me for a sec)

Basicly there is a Tile object that can be several types of tile, but instead of making those types extent a main Tile object the choice has been made to put the functionality into a sort of array,

tileTypes = {
    1: {
        color: red,
        func: dynamic_function(){
            //code here
        }
    },
    2: {
        color: green,
        func: dynamic_function(){
            //other code here
        }
    },
}

var Tile = function(type)
{
    this.color = tileTypes[type].color
    this.func = tileTypes[type].func
}

(The real life code is much larger then this, but it serves it's purpose as an example)

I know this isn't the nicest code out there (it feels really weird working like this) but it is highly dynamic and new types can be added very fast so I forgive it.

However, I don't know how to build this in python.

NOTE: I'll probably won't actualy use it, and instead, use some kind of mapping from the type id's to classes or something, but I am very curious if it would be even possible to make it like that)

Upvotes: 0

Views: 139

Answers (3)

alan
alan

Reputation: 4842

class TileType(object):
    def __init__(self, color, func):
        self.color = color
        self.func = func

tile_types = {
    1: TileType('red', some_func),
    2: TileType('green', some_other_func),
}

type = 1
tile = tile_types[type]

Upvotes: 1

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391396

This should get you started:

def tile1Func():
    return "tile 1"

def tile2Func():
    return "tile 2"

tileTypes = {
    1: {
        "color": "red",
        "func": tile1Func
    },
    2: {
        "color": "green",
        "func": tile2Func
    }
}

class tile():
    def __init__(self, type):
        self.color = tileTypes[type]["color"]
        self.func = tileTypes[type]["func"]

t1 = tile(1)
print("color: " + t1.color + ", name: " + t1.func())

Upvotes: 1

Marcin
Marcin

Reputation: 49846

class Foo: pass

def methodfunc(self, param): pass

Foo.mymethod = methodfunc

foo = Foo()
foo.mymethod(None)

The above will work, but only where instances are created after the class is patched.

Upvotes: 0

Related Questions