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.