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.

1
  • 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. Commented Jun 14, 2021 at 12:30

2 Answers 2

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

Comments

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.

1 Comment

using locals like that is horrible - uggh.

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.