1

I wrote a code:

class NewsStory(object):
    def __init__(self, guid, title, subject, summary, link):
        NewsStory.guid = guid
        NewsStory.title = title
        NewsStory.subject = subject
        NewsStory.summary = summary
        NewsStory.link = link

    def getGuid(self):
        return self.guid

    def getTitle(self):
        return self.title

    def getSubject(self):
        return self.subject

    def getSummary(self):
        return self.summary

    def getLink(self):
        return self.link

When I added an instance as:

test = NewsStory('foo', 'myTitle', 'mySubject', 'some long summary', 'www.example.com')

print test.getGuid() gives me foo, which is correct. However, if I continuously created two instances:

test = NewsStory('foo', 'myTitle', 'mySubject', 'some long summary', 'www.example.com')
test1 = NewsStory('foo1', 'myTitle1', 'mySubject1', 'some long summary1', 'www.example1.com')

both print test.getGuid() and print test1.getGuid() gave me foo1 but no foo. Why does it happen? And is there a method that I can modify my class definition or functions inside the class to avoid the new created instance overwriting the old one?

Thank you.

3 Answers 3

3

You'll need to make those variables in your __init__ function instance variables instead of class variables.

Instance variables look like this:

self.guid = guid

Class variables look like this:

NewsStory.guid = guid

Class variables are the same for all members of the class, but instance variables are unique to that instance of the class.

Sign up to request clarification or add additional context in comments.

Comments

1

The __init__ method is called after an instance of the class is created. The first argument, called self by convention, is the instance of the class. NewsStory is the class itself.

In your code, you're creating class variables. You want instance variables:

self.guid = guid

Comments

1

You are modifying class variables, which are common to all the objects. What you should do is to create those variables in the object, like this

    self.guid = guid
    self.title = title
    self.subject = subject
    self.summary = summary
    self.link = link

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.