1

if I want to use input as Variables name in OOP and Classes how should i do it:

class animal:
    def  __init__(self,name,age):
        self.name = name
        self.age = age
    def display_age(self):
        print("{} Age: {}".format(self.name,self.age))

def create():
    name = input("enter name: ")
    age = input("enter age: ")
    name = animal(name,age)

create()
Ben.display_age()

output:

enter name: Ben

enter age: 12

NameError: name 'Almog' is not defined

6
  • 2
    You should become familiar with Python scopes and namespaces. create returns nothing, so the name object is simply garbage collected (deleted) at the end of the function. You can't create a variable named Ben by assigning a variable name the value Ben, then changing that value. Commented Feb 24, 2018 at 14:27
  • so how should I perform new item to the class by user inputs? Commented Feb 24, 2018 at 14:30
  • "if I want to use input as Variables name" Then you should reconsider and use a dictionary instead. Commented Feb 24, 2018 at 14:35
  • Possible duplicate of How do I create a variable number of variables? Commented Feb 24, 2018 at 14:35
  • You don't mix it that way. That looks odd, to put user interface logic inside classes that have nothing to do with an user interface. You are mixing different concerns. Write your class. Somehow get data from user, and Instantiante an object from your class with somename = YourClasss(somedata) using that data as arguments to the __init__(). Your Animal is an animal, it does not know anything about mouses clicks or keyboards or input() Commented Feb 24, 2018 at 14:38

2 Answers 2

2

Hope this helps. Here you need to use the object which has been created.

class Animal:
    def  __init__(self,name,age):
        self.name = name
        self.age = age

    def display_age(self):
        print("{} Age: {}".format(self.name,self.age))

def create():
    name = input("enter name: ")
    age = input("enter age: ")
    return Animal(name, age)

a = create()
a.display_age()
Sign up to request clarification or add additional context in comments.

Comments

1

Here's a function that does something similar. We will store Animal objects inside a dictionary, using the name of each object as its key.

class Animal:
    def  __init__(self,name,age):
        self.name = name
        self.age = age
    def display_age(self):
        print("{} Age: {}".format(self.name,self.age))

def create(storage):
    name = input("enter name: ")
    age = input("enter age: ")
    storage[name] = Animal(name,age)

storage = {}
create(storage)
storage['Ben'].display_age() # If you didn't use Ben as the name, this will fail with a KeyError

1 Comment

But how can the user can display the age (with the func) using inputs?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.