簡體   English   中英

訪問實例變量,但不能訪問Python中的實例方法

[英]Access to instance variable, but not instance method in Python

我是python的新手,我想有人問過類似的問題(包括這個問題: 您可以使用字符串在python中實例化一個類嗎? ),但我不理解答案或如何使用它們。

我正在嘗試使用列表中的“實例名稱”創建一個類的多個實例。

這是我要執行的操作的一個示例:

class InstanceNames():
    def __init__(self):
        self.names = ['inst1', 'inst2', 'inst3']

class DoSomething():
    instances = []
    def __init__(self):
        DoSomething.instances.append(self)

instance_names = InstanceNames()
for x in range(len(instance_names.names)):
    print x
    # following line not working at creating instances of DoSomething
    instance_names.names[x] = DoSomething()

print DoSomething.instances

我將列表更改為循環,現在獲得以下輸出:

0
1
2
[<__main__.DoSomething instance at 0x10cedc3f8>, <__main__.DoSomething instance at 0x10cedc440>, <__main__.DoSomething instance at 0x10cedc488>]

奏效了嗎? 我很困惑,我不確定。

好。 這是一些丑陋的代碼,但這是我現在擁有的:

class InstanceNames():
    def __init__(self):
        self.i_names = {'inst1': None, 'inst2': None, 'inst3': None}
        self.o_names = ['foo', 'bar', 'baz']

class DoSomething():
    instances = []
    def __init__(self, blah_blah):
        DoSomething.instances.append(self)
        self.name = blah_blah

    def testy(self, a):
        a = a * 2

instance_names = InstanceNames()

for x in range(len(instance_names.i_names)):
    print x
    instance_names.i_names[x] = DoSomething(instance_names.o_names[x])

print "\n"

print DoSomething.instances

print "\n"

for y in DoSomething.instances:
    print y.name
    print y.testy(4)
    print "\n"

這是我的輸出:

0
1
2


[<__main__.DoSomething instance at 0x10dc6c560>, <__main__.DoSomething instance at 0x10dc6c5a8>, <__main__.DoSomething instance at 0x10dc6c5f0>]


foo
None


bar
None


baz
None

為什么打印“名稱”變量,但不打印“ testy”方法?

您似乎在問“我如何使用字符串'inst1'並創建一個名為'inst1'的變量”。

答案是您不想這樣做。 而是創建一個字典或列表,將您的字符串映射到相關對象。 有關示例,請參見此問題

(如果不是您要問的,請澄清您的問題。)

我不知道您實際上要做什么,以解決您的特定代碼,列表只是值的集合。 您將其視為一種dict,即鍵和值之間的關聯。

為了使示例正常工作,您可以使用dict:

class InstanceNames():
    def __init__(self):
        self.names = {'inst1': None, 'inst2': None, 'inst3': None}

現在,這將使以下表達式成功:

instance_names.names[x] = DoSomething()

...由於names現在是字典,因此您正在訪問鍵並為其分配值。

再次聲明,我不知道該代碼將要執行的操作……感覺可能不好……但沒有從判斷的角度出發。

instance_names.names是一個列表 ,需要數字作為索引。 實際上,您發布的TypeError表示相同的內容。

但是,您要使用instance_names.names[x]的字符串設置元素-其中x是字符串。 列表不允許這樣做,您需要為此使用字典

有幾種方法可以解決您的問題:

  1. 首先,您可以為instance_names.names使用字典。 然后,對於尚未創建的實例,必須使用諸如None類的保留對象作為占位符:´self.names = {'inst1':None,'inst2':None,'inst3':None} , and you must iterate through the keys of the dictionary: instance_names.names.keys()中的x表示:

  2. 您可以為實例使用單獨的字典,並在循環中設置其內容: self.instances = {} instance_names.instances[x] = ...

為了進一步了解Python的數據類型,我推薦使用Dive Into Python

您可以使用type動態創建類:

type_names = ["Class1", "Class2", "Class3"]
storage = {}
for t in type_names:
    storage[t] = type(t, (object, ), {"your": "instance", "attributes": "here"})

for type_name in storage:
    print type_name, "=>", storage[type_name]

或者,如果您真正需要的只是一堆屬性,則可以使用collections.namedtuple生成輕量級類。

現在有什么是創造的三個實例DoSomething類並在替換字符串值(不使用) InstanceNames類的names屬性與這三個實例DoSomething

or x是什么意思?

self.names在范圍內不存在,請改用instance_names.names

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM