0

I'm quite new at this language and I've been facing the following trouble:

I have defined a class and I want to create multiple objects of that class using a function, but this doesn't seem to work

class age:
    def __init__ (self):
        self.age = value

def function (name):
    global value
    value = 27
    name = age()

function("anna")
print "Age:", anna.age

Output:

Traceback (most recent call last):
  File "test.py", line 15, in <module>
    print "Age:", anna.age
NameError: name 'anna' is not defined

Trying different thing I found this will work. I don't understand the difference between them... The problem is that I had to leave the variable value in the environment. And I can't do this since my actual uses too many variables that might overlap with it, I mean, that have the same name.

class age:
    def __init__ (self):
        self.age = value

def function ():
    global value
    value = 27

function()
anna = age() 
print "Age:",anna.age

Output:

Age: 27

I would like to make the first code to work... Any advice or ideas? Thank you!

  • @jonrsharpe That is a very bizarre interpretation of the question. I just _cannot_ see how that linked duplicate is in _any way related_. Perhaps you can enlighten me... – Eithos Feb 12 '15 at 22:01
  • @Eithos the OP wants to use the `name` argument to function as the actual name through which the object is referenced, expecting `name = age()` to work like `anna = age()`, since `name == 'anna'`. The duplicate is the canonical answer for using strings as names, or "variable variables" as the original OP (OOP?) had it. – jonrsharpe Feb 12 '15 at 22:06
  • @jonrsharpe My mind = blown. I kept going over that yesterday wondering what the OP meant with `name = age()`. My hat's off to you. The only remaining point I'd make is that this part of his code was peripheral to his actual question, which from what I understood is figuring out how to extract an object after it's been created in a function. Still, I'm sure there's a ton of duplicates for _that_. – Eithos Feb 12 '15 at 22:15

1 Answers1

3

There are several mistakes here. I should start by saying you need to brush up on your knowledge (read the docs, look at more tutorials, etc). So first, you do need to return the object you've just created. So:

def function (name):
    global value
    value = 27
    name = age() # This is weird. You've passed in `name`, only to re-assign it.
    return name # Very important

anna = function("anna")
print "Age:", anna.age

Secondly, the class doesn't make much sense... It shouldn't be called age, only to have an age attribute. I recommend the following adjustments (in my humble opinion):

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

def createPerson(age, name):
    return Person(age, name)

anna = createPerson(27, "anna")
print "Age:", anna.age

But with such a simple function, however, you're almost just better off declaring the instance in your global scope:

anna = Person(27, "anna")
print "Age:", anna.age

Note:

Your second version works because of scope. This is a fundamental concept in programming languages. When you define a variable/name-identifier, your ability to reference it again will depend on the scope it was defined in. Functions have their own scope, and trying to reference a name created inside of it from the outside doesn't work.

As I've shown you, another fundamental part of programming is the ability to use a return statement that allows you to catch the result and use it outside of where it was created originally (the function in this case).

One Last thing

I noticed you meant to use the global keyword to declare value and use that to define your self.age inside of your age class. Never do that; that's what the constructor is for (__init__). As I've shown you in the above examples, you can easily pass parameters to it (def __init__(self, age, name)).

Finally, I'll say this: The use of the global keyword exists for a reason, as there may be situations where it's warranted. I personally don't use it and don't see it used very often at all. There's a good reason for that, which you may come to understand later and which is really outside the scope of this question. Just bear in mind that it's usually unnecessary to declare variables global inside a function and that it usually resutls in bad code in the long run.

You'll be much better off in the beginning (and in the future, too) if you get used to passing parameters around.

Eithos
  • 2,421
  • 13
  • 13