简体   繁体   English

在python 2.7中创建类的实例

[英]create an instance of class in python 2.7

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. print test.getGuid()给我foo ,这是正确的。 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 . print test.getGuid()print test1.getGuid()都给了我foo1但没有给我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. 您需要在__init__函数实例变量而不是变量中创建这些变量。

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. 类变量对于该类的所有成员都是相同的,但是实例变量对于该类实例是唯一的。

The __init__ method is called after an instance of the class is created. 创建该类的实例后,将调用__init__方法。 The first argument, called self by convention, is the instance of the class. 第一个参数,按惯例称为self ,是类的实例。 NewsStory is the class itself. NewsStory本身就是课程。

In your code, you're creating class variables. 在代码中,您正在创建类变量。 You want instance variables: 您需要实例变量:

self.guid = guid

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM