#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Location
    Canada
    Posts
    51
    Rep Power
    1

    Function to create class instances


    Hey would anyone know how to create a function that can create instances of a class with custom names. For example, with a class called Account, you can assign variables 'x = Account()'. Does anyone have a suggestion how I can create a function that would work like
    Code:
    create(x):
        x = Account()
    thanks, Ryan
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,711
    Rep Power
    480
    I can't really decipher your intent. This code is my best guess. It places a variable given as a string into the global name space. The variable takes the value of an instance of a class, which is also passed to the function as a string, along with the constructors arguments. Why would you make a variable that's difficult to access? A better plan: store objects into a dictionary that you can access by key, or into a tuple or list accessible by index.
    Code:
    '''
        Result of running this horrid beast.
    
        $ python3 p.py
        {'__loader__': <_frozen_importlib.SourceFileLoader object at 0x02A57D10>, '__file__': 'p.py', 'f': <function f at 0x02A4DAE0>, '__builtins__': <module 'builtins' (built-in)>, '__doc__': None, '__package__': None, '__cached__': None, '__name__': '__main__', 'BAD': 'IDEA'}
        IDEA
    '''
    
    
    def f(x, c, *args, **kwargs):
        assert isinstance(x, str)
        assert isinstance(c, str)
        exec('global {}; {} = {}(*args, **kwargs)'.format(x,x,c),globals(), locals())
    
    f('BAD','str','IDEA')
    print(vars())
    print(eval('BAD'))   # can use eval to access the variable
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    76
    Rep Power
    2
    You're just asking for how to make an initializer?


    Code:
    class Account():
        def __init__(self,name=''):
            self.name=name
        def __repr__(self):
            return 'Account:'+self.name
    Probably a little above and beyond the call, but it does that and takes a name parameter which it returns.

    Try:
    x=Account('Phil')
    y=Account()
    print(x,y)

    Then take that code apart and figure out what does what.
    That's how you learn to code.
    @Dave: I think he has background in some other language, maybe Lua or something. If not, just needs some practice describing problems in-depth.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Location
    Canada
    Posts
    51
    Rep Power
    1
    Originally Posted by Mr909
    You're just asking for how to make an initializer?


    Code:
    class Account():
        def __init__(self,name=''):
            self.name=name
        def __repr__(self):
            return 'Account:'+self.name
    Probably a little above and beyond the call, but it does that and takes a name parameter which it returns.

    Try:
    x=Account('Phil')
    y=Account()
    print(x,y)

    Then take that code apart and figure out what does what.
    That's how you learn to code.
    @Dave: I think he has background in some other language, maybe Lua or something. If not, just needs some practice describing problems in-depth.
    That's not what I meant. Sorry I guess I was more vague than I thought. I'm working on a budget program, it consists of 1 class, called Account. The program then has one main function in a loop that allows the calling of other functions. Every other function calls the main function after they complete to return to the choice loop. I wanted to be able to have a function called create(x,y,z): that would take x as the variable name for the class instance and any other argument as class arguments. Each instance of the Class would have a balance and a transaction log(similar to the example you posted dave). After a bit of googling, and Dave's post I'm starting to realize I'm going at it the wrong way.
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    76
    Rep Power
    2
    Initializers are functions that take the first as a name, the rest as arguments, and return class instances.

    It's the clearest, most concise way to describe that.

    I mean, I have seen other recipes that justify cases where you might not want to have the initializer serve to create instances, instead handling it with another function (Stackless comes to mind), but that should work for that.

    On that note, have you considered Stackless? If you're thinking about a program that deals with a main loop, introduce a new step then returning to the main, I hear "stackless" in my mind.

    EDIT: Ohhhh... NAME! Now I get it. Like namespace name. Yeah, that requires exec. Yeah, you also shouldn't do that. Sorry, I understand now. My apologies. :P
    Last edited by Mr909; August 3rd, 2013 at 03:28 PM.
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Location
    Canada
    Posts
    51
    Rep Power
    1
    Originally Posted by Mr909
    Initializers are functions that take the first as a name, the rest as arguments, and return class instances.

    It's the clearest, most concise way to describe that.

    I mean, I have seen other recipes that justify cases where you might not want to have the initializer serve to create instances, instead handling it with another function (Stackless comes to mind), but that should work for that.

    On that note, have you considered Stackless? If you're thinking about a program that deals with a main loop, introduce a new step then returning to the main, I hear "stackless" in my mind.

    EDIT: Ohhhh... NAME! Now I get it. Like namespace name. Yeah, that requires exec. Yeah, you also shouldn't do that. Sorry, I understand now. My apologies. :P
    For my little banking/budget program, I originally wanted to have an Account class that each account would be an instance of, it worked using the interpreter but probably wouldn't have worked for a stand alone program. I've since change it to a data structure, that consists of a dictionary with each account being an item in that dictionary and has a list containing everything related to that account. I'm finding that this is working much better than the original class did, I can now easily edit 1 or many class at once and saving the database of accounts is now very simple using pickle. I am using a main loop, that can call any of my functions and every functions call it upon completion. I haven't had any issues with this yet and seems to work well but I will take a look at stackless.
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    191
    Rep Power
    2
    Originally Posted by Mr909
    Yeah, that requires exec
    Actually you can get cute and do this:
    Code:
    >>> globals()["my_var"] = 25
    >>> my_var
    25
    or this:
    Code:
    >>> __builtins__["my_other_var"] = "Look at me go"
    >>> my_other_var
    'Look at me go'
    Of course you shouldn't... but you can.

    -Mek

IMN logo majestic logo threadwatch logo seochat tools logo