繁体   English   中英

在Python类中访问和列出属性

[英]Accessing and listing attributes in a Python class

我已经在Python的类结构内创建了一个类。 最后,我尝试检索其属性之一( price )的列表以sum所有值并对其进行数学运算。

它一直告诉我,我的类TOOLBOX或类DATA都没有属性Price 我该如何解决?

我的代码如下所示:

class DATA:
    def __init__(self, Identifier, Price, Date, Postcode, Type, Age, Tenure, Primary, Secondary, Street, Locality, Town, District, County, Status):
        self.Identifier = Identifier
        self.Price = Price
        self.Date = Date
        self.Postcode = Postcode
        self.Type = Type
        self.Age = Age
        self.Tenure = Tenure
        self.Primary = Primary
        self.Secondary = Secondary
        self.Street = Street
        self.Locality = Locality
        self.Town = Town
        self.District = District
        self.County = County
        self.Status = Status

class TOOLBOX(object):

    def __init__ (self):
        self.alldata = []

    def add_data(self, Identifier, Price, Date, Postcode, Type, Time, Tenure, Primary, Secondary, Street, Locality, Town, District, County, Status):
        self.alldata.append(DATA(Identifier, Price, Date, Postcode, Type, Time, Tenure, Primary, Secondary, Street, Locality, Town, District, County, Status))

    def get_prize(self) :
        price=[]
        for line in self.alldata:
                price.append(self.alldata.Price)
        print price

    def summation(self):
        return sum(self.alldata.Price)



csv_ff = csv.reader(open("FINAL.csv",'rU'))
l=len(list(csv.reader(open("FINAL.csv",'rU'))))

dd = TOOLBOX()

for line in csv_ff:
    if len(line)==15:

        Identifier=line[0]
        Price=int(line[1])
        Date=line[2]
        Postcode=line[3]
        Type=line[4]
        Age=line[5]
        Tenure=line[6]
        Primary=line[7]
        Secondary=line[8]
        Street=line[9]
        Locality=line[10]
        Town=line[11]
        District=line[12]
        County=line[13]
        Status=line[14]

        dd.add_data(Identifier, Price, Date, Postcode, Type, Age, Tenure, Primary, Secondary, Street, Locality, Town, District, County, Status)

Price是存储在self.alldata列表中的DATA实例的self.alldata 因此,您需要遍历self.alldata列表并获取Price属性,如下所示:

def get_prices(self) :
    prices=[]
    for line in self.alldata:
         price.append(line.Price)
    return prices

笔记:

  1. 我将方法从get_prize重命名为get_prices
  2. get_prices()现在返回价格列表,而不仅仅是打印它们。
  3. 如果get_prices()要打印价格列表,则最好使用display_prices()或类似get_prize()建议该方法返回一个值。

然后,您的求和方法可以通过调用get_prices()来获取价格列表并对它们求和:

def summation(self):
    return sum(self.get_prices())

您正在尝试使用allData列表访问属性:

self.alldata.Price # incorrect 

self.Price # correct

self.PriceDATA类的属性, self.alldata是包含DATA实例的列表,您需要遍历该列表并调用类似ele.Price的属性,以访问ele.Price中ele表示for ele in self.alldata :....

您基本上是想在列表上执行[].Price ,列表肯定没有Price方法,所以这将失败。

    def get_prize(self) :
        price = []
        for line in self.alldata: # stores instances of DATA
              price.append(line.Price) # access attribute using the instance
        print price

def summation(self):
    return sum(inst.Price for inst in self.alldata) # again access using instance 

如果更改get_prize方法以返回价格列表:

     def get_prize(self) :
            price = []
            for line in self.alldata: # stores instances of DATA
                  price.append(line.Price) # access attribute using the instamce
            return  price

我们可以简单地使用该方法求和:

    def summation(self):
        return sum(self.get_prize())

我们还可以在get_prize返回一个列表理解,它更简洁一些,并使用一个更能描述每个元素是什么的变量:

def get_prize(self) :
    return  [inst.Price for inst  in self.alldata]

附带说明,属性等使用小写和下划线self.price, identifier self.all_data ...

您的DATA类确实具有属性-不具有Price属性的是attr。 alldataTOOLBOX 。它仅仅是一个列表。

尽管在Python中构建序列对象可以以“ jQueriest”方式表现是可能,容易和有趣的-也就是说:在需要序列中的属性时,为序列中的所有对象检索该属性的序列,这不是语言的默认行为-如果没有专门的班级,做toolbox_object.alldata.Price尝试检索Price的属性alldata

要检索所有价格的序列(作为生成器表达式),您应该编写:

(elem.Price for elem in toolbox_object.alldata)

因此,您的代码行:

def summation(self):
    return sum(self.alldata.Price)

你应该有:

def summation(self):
    return sum(element.Price for element in self.alldata)

(顺便说一句,您的DATA类也应继承自“对象”)

现在,有趣的是,如果您想要类似jQuery的属性检索,则可以使用额外的__getattr__方法从Python的列表中创建派生类-该方法应该可以工作(可以实现真正的“按书”,“产品就绪”功能)与抽象基类,等等-但这是可行的):

class JQList(list):
     def __getattr__(self, attr):
          return [getattr(element, attr) for element in self]

>>> import random
>>> 
>>> b = JQList()
>>> b = JQList(random.randint(0,10) + random.randint(0,10) * 1j for i in range(10) )
>>> b
[(5+7j), (3+4j), 3j, (4+9j), (1+9j), (2+3j), (1+0j), (10+4j), 9j, (9+10j)]
>>> b.real
[5.0, 3.0, 0.0, 4.0, 1.0, 2.0, 1.0, 10.0, 0.0, 9.0]
>>> b.imag
[7.0, 4.0, 3.0, 9.0, 9.0, 3.0, 0.0, 4.0, 9.0, 10.0]

此代码的更多提示 -(有关您问题的答案,请查看我的其他答案)

Python是一种允许人们真正编写简短且易读的代码的语言-在这个小示例中,您将15个属性的名称重复---重复7次---这是很多键入属性名称的方法:-)

因此,无需对代码进行任何更改,如果您知道将从csv文件中按顺序获取属性,并且不应该更改,则只需将实例化代码更改为:

对于csv_ff中的行:如果len(line)== 15:dd.add_data(* line)

在行序列之前的“ *”将在调用.add_data的位置参数中“展开”其每个元素。 -这将删除所有变量名称。

您可以在add_data方法中执行相同add_data -可以是add_data

def add_data(self, *args):
    self.all_data.append(DATA(*args))

function(/ method)定义中的“ *”只是告诉Python接受所有剩余的位置参数,并将它们放在名称为“ args”的列表中。 我们不在那儿使用argumetns,我们只是通过它们。 按原样折叠到DATA对象构造函数。 请注意,这还会使TOOLBOX类与对象的特定属性分离。

有一些技巧也可以缩短DATA的实现方式,但是会在可读性/复杂性之间进行权衡。 (尽管很小)

我认为这可能是一个简单的解决方案:

class DATA:
def __init__(self,Price):   # skipped other parameters    
    self.Price = Price

class TOOLBOX(object):

def __init__ (self):
    self.alldata = []

def add_data(self, Price):
    self.alldata.append(DATA(Price))

def get_prize(self) :
    price=[]
    for line in self.alldata:
            price.append(line.Price)
    print(price)
    return price

def summation(self):
    return sum(self.get_prize())

# use example
T=TOOLBOX()
T.add_data(2)
T.add_data(3)
print(T.summation())
# 5

get_prize()可以写得更优雅:

 def get_prize(self) :
    price = [line.Price for line in self.alldata]
    print(price)
    return price

暂无
暂无

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

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