在Python中访问实例变量,而不是实例方法 [英] Access to instance variable, but not instance method in Python

查看:215
本文介绍了在Python中访问实例变量,而不是实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,我认为类似的问题已被问过(包括这个:),但我不明白答案或如何应用它们。



我试图创建一个类的多个实例,我将在列表中调用实例名称。



这里是我想要做的一个例子:

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

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

instance_names = InstanceNames()
范围内的x(len(instance_names.names)):
print x
#下面的行不能创建DoSomething实例
instance_names.names [x] = DoSomething()

print DoSomething.instances

我改变了循环列表,现在我得到以下输出:

  0 
1
2
[<__ main __。在0x10cedc3f8的DoSomething实例>,< __ main __。在0x10cedc440的DoSomething实例,< __ main__ .DoSomething instance at 0x10cedc488>]

有效吗?我很困惑,我不确定。



好的。这是一些丑陋的代码,但这里是我现在:

 类InstanceNames():
def __init __ ):
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()

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

打印\\\


在DoSomething.instances中为y:
print y。 name
print y.testy(4)
print\\\

这是我的输出:

  0 
1
2

b $ b [< __ main __。DoSomething instance at 0x10dc6c560>,< __ main __。DoSomething instance at 0x10dc6c5a8>,< __ main __。DoSomething instance at 0x10dc6c5f0>]


foo



bar



baz

为什么'name'变量打印,但是'testy'方法不是?

解决方案

您可以使用 type 动态创建类:

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

用于存储中的type_name:
print type_name,=>,storage [type_name]
pre>

或者,您可以使用 collections.namedtuple 生成轻量级类,如果你真正需要的是一堆属性。



您目前有创建 DoSomething 类的三个实例,属性中 InstanceNames 属性的字符串值c $ c> DoSomething


I'm a newbie to python and I think similar question have been asked (including this one: Can you use a string to instantiate a class in python?), but I don't understand the answers or how to apply them.

I'm trying to create multiple instances of a class using what i'll call 'instance names' in a list.

Here's an example of what I'm trying to do:

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

I changed the list for loop, and now I'm getting the following output:

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

did it work? I'm so confused i'm not sure.

Ok. This is some ugly code, but here's what I have now:

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"

Here is my output:

0
1
2


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


foo
None


bar
None


baz
None

Why is the 'name' variable printing, but the 'testy' method is not?

解决方案

You can use type to create classes dynamically:

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]

Alternately, you can used collections.namedtuple to generate lightweight classes if all you really need is a bunch of attributes.

What you currently have is creating three instances of the DoSomething class and replacing the string values (which you don't use) in the InstanceNames class' names attribute with these three instances of DoSomething.

这篇关于在Python中访问实例变量,而不是实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆