0

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)

3 Answers 3

1

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())
Sign up to request clarification or add additional context in comments.

1 Comment

Shame there is no way of defining the actual function inside the dictonairy... oh well, I guess this does come closest :)
1
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]

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.