Python引用实例列表变量

时间:2014-04-25 03:24:10

标签: python

我刚开始学习Python,而且我在实例变量上苦苦挣扎。所以我在一个列表类型的方法中创建一个实例变量。稍后,我想调用并显示该变量的内容。但是,我遇到了这样的问题。我在网上看了一些,但我还是无法上班。我正在考虑以下内容(这是一个简化版本): 这样做的正确方法是什么?

    class A:
        def _init_(self):
            self.listVar = [B("1","2","3"), B("1","2","3")]
        def setListVal():
            #Is this needed? Likewise a "get" method"?
        def randomMethod():
            A.listVar[0] #something like that to call/display it right? Or would a for  
                         #for loop style command be needed?

     Class B:
        def _init_(self):
            self.a = ""
            self.b = ""
            self.c = ""

2 个答案:

答案 0 :(得分:0)

列表是否会在您创建实例时传递给实例(即每次都不同)?

如果是这样,试试这个:

class A:
    def __init__(self, list):
        self.listVar = list

现在,当您实例化(读取:创建实例)类时,可以将列表传递给它,它将保存为该实例的listVar属性。

示例:

>>> first_list = [B("1","2","3"), B("1","2","3")]
>>> second_list = [C("1","2","3"), C("1","2","3")]
>>> first_instance = A(first_list)  # Create your first instance and pass it your first_list. Assign it to variable first_instance
>>> first_instance.listVar  # Ask for the listVar attribute of your first_instance
[B("1","2","3"), B("1","2","3")]  # Receive the list you passed
>>> second_instance = A(second_list)  # Create your second instance and pass it your second_list. Assign it to variable second_instance
>>> second_instance.listVar  # Ask for the listVar attribute of your second_instance
[C("1","2","3"), C("1","2","3")]  # Receive the list you passed second instance

随意询问是否有任何不清楚的事。

答案 1 :(得分:0)

class A:
    def __init__(self):
        self.listVar = [B("1","2","3"), B("1","2","3")]
    def setListVal(self, val):
        self.listVar[0] = val # example of changing the first entry
    def randomMethod(self):
        print self.listVar[0].a  # prints 'a' from the first entry in the list

class B:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

我做了几处改动。您需要使用self作为所有方法的第一个参数。该参数是您引用所有实例变量的方式。初始化函数是__init__注意,前后是2个下划线。您正在传递三个参数来初始化B,因此除了self之外,您还需要有3个参数。