though i'm calling pr() function in the subclass after calling the get_details() function(which assigns value to name) it doesn't print the current value of name.
Actually, it is printing the current value of name. The employee.name is always a space (' '), because you never change it. In your get_details function, you have created a new variable called name and assigned the users' input to it. Why don't you try printing x.name after your call to x.get_details()? You'll see that x.name is still just a blank space. The problem is that then name object that you're creating inside get_details only exists inside the scope of that function. You should be using self.name, which is the persistent attribute of the employee class. Let me demonstrate this principle:
>>> class no_init(object):
... name = 'I have no init function'
... def print_name(self):
... name = input('Input some name: ')
... print('self.name', self.name)
... print('name', name)
...
>>> ni = no_init()
>>> ni.print_name()
Input some name: Testing
self.name I have no init function
name Testing
>>> ni.name
'I have no init function'
As you can see, the name attribute is always "I have no init function" even though there is a "
name " inside my
print_name function. This is because that particular object is created and destroyed inside that function only. To refer to an attribute of a class from inside the class declaration you need to use
self. , whereas outside the class you use the object's instance. So in the above I used
ni.name as
ni is the instance of the
no_init class and name is the attribute I'm looking for.
The following code is identical but uses an init function instead (this is the recommended way to do classes, and it's good to get into the habit of using them):
>>> class yes_init(object):
... def __init__(self):
... self.name = 'I have no init function'
... def print_name(self):
... name = input('Input some name: ')
... print('self.name', self.name)
... print('name', name)
...
>>> yi = yes_init()
>>> yi.print_name()
Input some name: Testing 2
self.name I have no init function
name Testing 2
>>> yi.name = 'New name'
>>> yi.print_name()
Input some name: Testing 3
self.name New name
name Testing 3
>>>
You see inside the init function I immediately started referring to the attribute
name as
self.name . This makes it easier for a casual reader of code to identify which name is which.
HTH