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.
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.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句