0

Lets say I have a simple console program where user can input some text. And suppose I have class as follows:

class A:
    def __init__(self, some_string):
        self.lens=len(some_string)
    
    def PrintLen(self):
        print(self.lens)

Suppose that user input some text consisting of only one word (lets say - 'word'). My question is how can I make 'word' to become instance of class A that I can use word.PrintLen() without any errors? I guess I should implement some function that converts string object to my class object but I don't know how to realize that.

KiNest
  • 55
  • 1
  • 5
  • it would be far better to use the user input as a key into a dictionary, and the new instance to be the value. The problem you have is when you type 'word.Printitem()` in your code you have already determined the name of your instance. – Tony Suffolk 66 Jun 14 '21 at 12:30

2 Answers2

2

A far better solution instead of trying to create a new variable based on whatever the user inputs, it would be more 'sensible' to make use of dictionaries.

A dictionary contains pairs of keys and values so your key would be the input value and the value would be the instance of class.

your code would be like this :

class A:
    def __init__(self, some_string):
        self.lens=len(some_string)

    def PrintLen(self):
        print(self.lens)

instances = {}
name = input('WHat is your name >')
instances[name] = A(name)

you will then use it like this :

instances[name].PrintLen()
Tony Suffolk 66
  • 9,358
  • 3
  • 30
  • 33
0

I'm sensing some anti-patterns here. The key thing you're looking to do based on your question is set the user's input to the name of a variable - of an instance of your class. I don't know if that's necessarily the best way to do it for your use case. Maybe it could be better to always name the variable the same thing but add a self.string parameter to your A class.

If you do want to do that see here. You would write

in_string = raw_input("Enter string:")
locals()[in_string] = A(in_string)

Then you could call the PrintLen function as you described.

Chris Schmitz
  • 618
  • 1
  • 6
  • 16