【发布时间】:2014-01-31 10:08:32
【问题描述】:
在我的 Python 作业简介中,我创建了类的实例,存储在列表中。我可以按它们在列表中的位置打印或删除它们,但实际上,我需要能够查询单个属性,例如只过滤可用的属性、更改它们的可用性或显示每个对象的成本。我会附上一些代码:
class Vehicle():
def __init__(self,plateno,kml,dailycost,weeklycost,weekendcost): #attributes common to all vehicles
self.plateno=plateno
self.kml=kml
self.dailycost=dailycost
self.weeklycost=weeklycost
self.weekendcost=weekendcost
self.avail=True
# methods
def __str__(self):b
return "Vehicle Plate Number: {0}, km/l: {1}, daily: {2},weekly: {3}, weekend: {4}".format(self.plateno, self.kml, self.dailycost, self.weeklycost, self.weekendcost)
def __del__(self):
return "Vehicle deleted: {0}".format(self.plateno)
class Cvn(Vehicle):
def __init__(self,plateno,kml,bedno,dailycost,weeklycost,weekendcost):
Vehicle.__init__(self,plateno,kml,dailycost, weeklycost, weekendcost)
self.bedno=bedno
def __str__(self):
return "Caravan: Plate Number: {0}, km/l: {1}, number of beds: {2}, daily: {3},weekly: {4}, weekend: {5}, Available? {6}".format(self.plateno, self.kml, self.bedno, self.dailycost, self.weeklycost, self.weekendcost, self.avail)
# I N S T A N C E S
# C A R A V A N S Class:Cvn
# (self,plateno,kml,bedno,dailycost,weeklycost,weekendcost)
#------------------
#caravanheaders=["Km/l","Number of beds","Plate number","Daily cost","Weekly cost","Weekend cost"]
cvn1=[12,4,"11-D-144",50,350,200]
cvn2=[10,6,"10-D-965",50,365,285] #values as per Caravan table
cvn3=[11,4,"12-C-143",50,350,200]
cvn4=[15,2,"131-G-111",50,250,185]
cvnslist=[cvn1,cvn2,cvn3,cvn4] #this list contains 4 variables, each representing a list, as above
cvns=[] #this is going to be the list of lists
for i in cvnslist: #this loop creates a list of lists 'cvns'
cvns.append(i)
print("")
print(cvns) #the list of lists
cvninstances=[]
for i in range(len(cvns)):
cvninstances.append(Cvn(cvns[i][2],cvns[i][0],cvns[i][1],cvns[i][3],cvns[i][4],cvns[i][5]))
vehlist.append(Cvn(cvns[i][2],cvns[i][0],cvns[i][1],cvns[i][3],cvns[i][4],cvns[i][5]))
# print(cvninstances) #this shows just that there are objects, but not their attibutes
#for i in cvninstances:
# print(i)
print("")
for i in vehlist:
print("On Vehicles List: ",i)
print("")
print("Initial fleet displayed.")
print("")
#---------------------------------------------------------------------------------
对于我来说不幸的是,这里对类似问题的大多数答案都处于更高级的水平!
【问题讨论】:
-
你知道如何获取实例的属性吗?
-
我知道我创建的一个对象,例如Student1=Student("Mary"),我可以通过调用Student1.name(Class being Student(self,name))得到Mary这个名字...
标签: python list class object instance