[Tutor] Trying to understand how object re-instantiation gets propagated

Alan Gauld alan.gauld at yahoo.co.uk
Wed Feb 17 07:22:36 EST 2021


On 17/02/2021 11:43, Dimitar Ivanov wrote:

> My JIRA issue class (shown below) retrieves the values from a JIRA server
> and saves them as instance variables. To avoid outdated information when I
> update a value on the JIRA server, I made a small function that retrieves
> the JIRA issue from the server again and re-instantiates a new object of my
> class:

No it doesn't. It reinitializes the same object.
initialization and instantiation are two different concepts and Python
separates them into two different methods. __new__() constructs new
instances __init__() initialises existing instances.

When you create a new object with

myObj = MyClass()

Python first calls myClass.__new__() to create an empty instance
Then calls MyClass.__init__() to initialize that instance.

> class JiraIssue:
>   def __init__(self, jira_issue):
>     self.key = issue.key
>     self.assignee = issue.fields.assignee
> 
>   def reload(self):
>     jira_issue = jira_connection.issue(self.key)    # Retrieving the issue
> from the JIRA server
>     issue = JiraIssue.__init__(self, jira_issue)

So this line just reinitialises the existing object it does
not create a new one.

> Python just "knows" that my_issue is now referring to the newly
> instantiated object by the reload() method.

There is no new object, its still the same one but with
updated values.

Incidentally, you don't really need objects here at all,
you could just create a dictionary with the issue attributes
in it.

myIssue = {'key':jira_issue.key, 'assignee': jira_issue.fiels.assignee}

Then write a reload() function to refresh the values.

To quote the YouTube video "Stop writing classes"
- "Any time you have a class with just an init() plus one
   method all you really need is a function"

Of course you may be planning on adding a bunch of other
methods, in which case just carry on with the class. :-)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list