2

In python, is there a way to make this work?

----------
# list of people
people = ["Nick", "Sue", "Bob"]

# class instance
Bob.pockets = ["gum", "paperclip", "coins"]

# convert string to prefix of a class instance
Print(people[2].pockets())

----------

This is the simplest way to show what I'm needing to figure out.

I need to convert a string into the prefix of a class instance.

I'm having trouble figuring it out.

Comments
  • 2
    A bit more context would be useful.

    Cab you store the instances in a dictionary with the strings as a key?
  • 1
    @sbiewald

    I'm working a building a simulated file system.

    When I connect to another I have a "connected machine" variable that changes to match.

    I'm trying to get my 'ls" command to show what is in the new machines directory instead of the local directory.

    https://github.com/Mung00se/...

    This is my current code for my project
  • 3
    There are ways to accomplish this...

    Eg. by using the GC functions (e.g. get_referents if I remember correctly).

    However... The approach is like taking a planet destroyer and trying to make marshmellows....

    A dict would be better suited for that.

    Best paired with an Enum in my opinion.

    I think I remember the code somehow... Or at least parts of it.

    We discussed the remote list thingy I think.

    Quick read over the code:

    - look at the Enum class in Python
    - https://martinheinz.dev/blog/70
    - Python f Strings (lower case f)
    - might want to take a look at pylint
    - might want to take a look at a code formatter (e.g. flake / black / ...)
    - should take a closer look at what dict is
    - better understand pythons variable scope

    E.g. the initialization of an object and writing to global variables is "smelly".
    (Class RemoteHost).

    Dict should be the right way for your problem.

    Variables of variables / reflection is a cumbersome thing - many languages allow it, matches what you want to do but I recommend taking another approach because it is in nearly all cases the wrong approach - many problems, no benefits.
  • 1
    Maybe take a look at factory pattern by the way.

    It seems like you want to create an object and ensure certain behaviour when the object is created...
  • 0
    @IntrusionCM

    I'll look into that and see if that is the solution
  • 1
    What about dictionaries? I know nothing about Python but usually dictionaries (a.k.a. hashed lists or "objects" in JS) are used for something like this in other languages.
  • 1
    You basically want to access a variable by name? Since you say class instance and not just class
Add Comment