访问python中的类对象时出错 [英] Error accessing class objects in python

查看:139
本文介绍了访问python中的类对象时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在访问类实例时遇到了一些问题。我从一个过程调用类,实例的名称在一些变量中定义。我想要的实例名称创建该值,然后想要访问它,但当我访问它是给错误。可能有人请帮助解决这个问题。

  class myclass:
def __init __(self,object):
self.name = object

def mydef():
全局a1
b =a1
b = myclass(b)

mydef()
print a1.name

第二个问题:
我的实际脚本,我必须从这个函数(大约100)创建大量的这样的实例。因此,将它们的名称定义为全局将是痛苦的,是否有一种方法我可以访问那些函数之外的实例,而不必声明为全局。



修改:

  class myclass:
def __init __(self,object,typename):
self.name = object
self.typeid = typename

def mydef():
file_han = open(file,r)
while True:
line = file_han.readline
如果不是行:
break
start = line.find('')
end = line.find('',start + 1)
string_f = line [start + 1:end]
myclass(s​​tring_f,'a11')

mydef(file)

print def.name
print def.typeid

文件内容是:
a11def
a11ghi
a11eff


解决方案

这是我要做的。我不知道你为什么要解决全局变量,如果你愿意解释,我会更新我的答案。

  class Myclass(object):
def __init __(self,name):
self.name = name

def mydef():
return Myclass a1)

a1 = mydef()
print a1.name


$ b b

在列表中收集您的实例:

  instances = [] 

instances.append(Myclass(Instance {0}。format(x)))
print instance [42] .name

请注意变更:




  • 类名称应大写。

  • 使用 object 作为类的基类(自python 2.2起,但不再需要在3.x中)

  • 不要使用您的参数名称影响内置的对象

  • 只需使用字符串 a1直接作为参数,而不是将其分配给变量

  • 从函数返回某个值,而不是通过全局变量传递结果



RE:评论



这些文件的格式,所以我只给一个例子,其中要读取的文件每行包含一个类名,没有其他:

  def mydef(filename):
ret = []
with open(filename)as f:
for line in f:
#行删除换行符和周围空格
ret.append(Myclass(line.strip()))
return ret

所以如果你有几个文件,并希望将所有的文件添加到一个大的列表中的所有实例,请这样做:



<$在[myfile1,myfile2,myfile3]中的文件名p $ p> instances = []
]:
instances.extend(mydef $ b

RE:OP编辑

  def mydef(filename):
ret = []
with open(filename,r)as file_han:
for line in file_han :
string_f = line.split(''')[1]
ret.append(Myclass(s​​tring_f))
return ret

i = mydef(name_of_file )

RE:评论



哦,你想通过名字访问它们。然后返回 dict

  def mydef b $ b ret = {} 
with open(filename,r)as file_han:
for line in file_han:
string_f = line.split('')[1]
ret [string_f] = Myclass(s​​tring_f)
return ret

i = mydef(name_of_file)
print i [ghi]。 ghi

RE:评论



如果我正确地理解你,你想要两种方式 - 通过行号和名称索引。那么为什么不返回列表和字典?

  def mydef(filename):
d = {}
L = []
with open(filename,r )as file_han:
for file_han:
string_f = line.split('')[1]
instance = Myclass(s​​tring_f)
d [string_f] = instance
L.append(instance)
return L,d

L,d = mydef(name_of_file)
print d [ghi]。name
print L [3]
print L.index(d [ghi])


I am having some problem accessing class instances. I am calling the class from a procedure, name of instance is defined in some variable. I want the instance name to be created of that value and then want to access it, but when i access it is giving error. Can some one please help to resolve this issue.

class myclass:
  def __init__(self,object):
    self.name = object

def mydef():
   global a1
   b = "a1"
   b = myclass(b)

mydef()
print a1.name

Second Problem: In my actual script, I have to create a large number of such instances from this function (around 100). So defining their name as global would be painful, is there a way i could access those instances outside function without having to declare them as global.

Modification:

class myclass:
    def __init__(self,object,typename):
        self.name = object
        self.typeid = typename

def mydef():
    file_han = open(file,"r")
    while True:
      line = file_han.readline()
      if not line:
        break
      start = line.find('"')
      end = line.find('"',start+1)
      string_f = line[start+1:end]
      myclass(string_f,'a11')        

mydef(file)

print def.name
print def.typeid

File Contents are :
a11 "def"
a11 "ghi"
a11 "eff"

解决方案

Here's how I'd do it. I don't know why you're messing around with globals, if you'd care to explain, I'll update my answer.

class Myclass(object):
    def __init__(self, name):
        self.name = name

def mydef():
   return Myclass("a1")

a1 = mydef()
print a1.name

Gather your instances in a list:

instances = []
for x in range(1000):
    instances.append(Myclass("Instance {0}".format(x)))
print instance[42].name

Note the changes:

  • Class names should be capitalized
  • Use object as the base class of your classes (since python 2.2, but no longer necessary in 3.x)
  • Don't shadow the built-in object with your parameter name
  • Just use the string "a1" directly as a parameter instead of assigning it to a variable
  • Return something from the function instead of passing the result by global variable

RE: Comment

You haven't said anything about the format of these files, so I'll just give an example where the file to be read contains one class name per line, and nothing else:

def mydef(filename):
    ret = []
    with open(filename) as f:
        for line in f:
            # Call `strip` on line to remove newline and surrounding whitespace
            ret.append(Myclass(line.strip()))
    return ret

So if you have several files and wish to add all your instances from all your files to a large list, do it like this:

instances = []
for filename in ["myfile1", "myfile2", "myfile3"]:
    instances.extend(mydef(filename))

RE: OP Edit

def mydef(filename):
    ret = []
    with open(filename, "r") as file_han:
        for line in file_han:
            string_f = line.split('"')[1]
            ret.append(Myclass(string_f))
    return ret

i = mydef("name_of_file")

RE: Comment

Oh, you want to access them by name. Then return a dict instead:

def mydef(filename):
    ret = {}
    with open(filename, "r") as file_han:
        for line in file_han:
            string_f = line.split('"')[1]
            ret[string_f] = Myclass(string_f)
    return ret

i = mydef("name_of_file")
print i["ghi"].name  # should print "ghi"

RE: Comment

If I understand you correctly, you want to have it both ways -- index by both line number and name. Well then why don't you return both a list and a dictionary?

def mydef(filename):
    d = {}
    L = []
    with open(filename, "r") as file_han:
        for line in file_han:
            string_f = line.split('"')[1]
            instance = Myclass(string_f)
            d[string_f] = instance
            L.append(instance)
    return L, d

L, d = mydef("name_of_file")
print d["ghi"].name
print L[3]
print L.index(d["ghi"])

这篇关于访问python中的类对象时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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