pythonoop:练习将一个方法的结果传递给另一个方法
对于我来说,这只是一个关于Python面向对象编程的一般性问题。我读过很多教程,但我很难将其应用到我自己的需要中。 我的问题围绕着如何在Python中为某些基本任务使用OOP。OOP可能不是解决这个问题的最佳方法,但这主要是一个使用我已经熟悉的数据结构的OOP示例。 我想要一个CSV文件,其中包含两个项目(本例中为宠物)及其各自的组合价格,例如:pythonoop:练习将一个方法的结果传递给另一个方法,python,oop,methods,parameter-passing,Python,Oop,Methods,Parameter Passing,对于我来说,这只是一个关于Python面向对象编程的一般性问题。我读过很多教程,但我很难将其应用到我自己的需要中。 我的问题围绕着如何在Python中为某些基本任务使用OOP。OOP可能不是解决这个问题的最佳方法,但这主要是一个使用我已经熟悉的数据结构的OOP示例。 我想要一个CSV文件,其中包含两个项目(本例中为宠物)及其各自的组合价格,例如: dog1,cat1,5.00 dog1,cat2,7.00 cat1,dog2,10.00 cat2,dog2,10.00 dog2,dog1
dog1,cat1,5.00
dog1,cat2,7.00
cat1,dog2,10.00
cat2,dog2,10.00
dog2,dog1,8.00
cat1,cat2,10.00
下面的代码是我到目前为止的代码,不是很好,但希望它足够清楚地解释我的问题。使用一个非常基本的OOP过程(无论我是否需要),我的目标是:
(1) 创建实例,并确定所需的变量
(2) 使用这些变量,创建字典,然后
(3) 将(2)的结果传递到另一个方法并解析此字典
最终,第一种方法创建了一个字典,如下所示:
{‘猫’:[10.0],‘狗’:[7.0,10.0,10.0],‘狗’:[8.0]}
然后,第二种方法生成:
['dog\uuu cat'、'dog\uu dog']
…因为这些是“便宜”的东西。正如最后所列,我想做的是在一行中调用这两个方法,使用一个方法调用另一个方法。
这是如何实现的
import sys
import numpy as np
infile=sys.argv[1]
class PriceParser:
def __init__(self, linesplit):
linesplit = line.split(",")
self.Pet1 = linesplit[0]
self.Pet2 = linesplit[1]
self.price = linesplit[2].rstrip("\n")
self.Pet1short = self.Pet1[0:3]
self.Pet2short = self.Pet2[0:3]
self.combo = self.Pet1short+"__"+self.Pet2short
self.comborev = self.Pet2short+"__"+self.Pet1short
self.PetSame = self.Pet1short+"__"+self.Pet1short
#dictPetPrices = {}
def PriceIdentifier (self):
if self.Pet1short != self.Pet2short:
if not self.comborev in dictPetPrices:
if not self.combo in dictPetPrices:
dictPetPrices[self.combo]=[]
dictPetPrices[self.combo]=[float(self.price)]
else:
dictPetPrices[self.comborev].append(float(self.price))
elif self.Pet1short == self.Pet2short:
if not self.PetSame in dictPetPrices:
dictPetPrices[self.PetSame]=[]
dictPetPrices[self.PetSame].append(float(self.price))
return dictPetPrices
def PriceSpectrum (self):
Cheap = []
for k,v in dictPetPrices.iteritems():
for i in v:
if float(i) <= 8:
Cheap.append(k)
return Cheap
if __name__ == '__main__':
with open(infile) as f:
dictPetPrices = {}
for line in f:
A = PriceParser(line)
B=A.PriceIdentifier()
print B
print A.PriceSpectrum()
#What I would prefer to do (below), is pass one method into another, if for instance, I have multiple methods that need to be called
#print A.PriceSpectrum(PriceIdentifier)
导入系统
将numpy作为np导入
infle=sys.argv[1]
类分析器:
def __;初始__;(自,行拆分):
linesplit=行分割(“,”)
self.Pet1=linesplit[0]
self.Pet2=linesplit[1]
self.price=linesplit[2]。rstrip(“\n”)
self.Pet1short=self.Pet1[0:3]
self.Pet2short=self.Pet2[0:3]
self.combo=self.Pet1short+“_uu”+self.Pet2short
self.comborev=self.Pet2short+“_uu”+self.Pet1short
self.PetSame=self.Pet1short+“_uu”+self.Pet1short
#价格={}
def价格标识符(自身):
如果self.Pet1short!=self.Pet2short:
如果不是self.comborev,价格:
如果价格中没有self.combo:
价格[self.combo]=[]
dictPetPrices[self.combo]=[float(self.price)]
其他:
dictPetPrices[self.comborev].append(float(self.price))
elif self.Pet1short==self.Pet2short:
如果不是self.pet,则价格相同:
dictPetPrices[self.PetSame]=[]
dictPetPrices[self.PetSame].append(float(self.price))
退货价格
def价格谱(自我):
便宜=[]
对于k,v,在dictPetPrices.iteritems()中:
对于v中的i:
如果float(i)您有一些正确的想法,但是您的代码结构不好。当您调用
PriceParser(linesplit)
时,您实际上是在调用PriceParser.\uuuu初始化\uuuuuuuu(self,linesplit)
。这是初始化成员变量的正确位置。因此,将第一组代码从PriceIdentifier
,向下移动到##注释,进入uuu init_uuu
。这将解决未定义变量名的问题
我不明白在##注释之后,您在代码中试图做什么。把你的问题放到文本中,而不是把它们埋在代码注释中,这将是一个好主意。顺便说一句,
self.Percentiles[:]=[]
行是不可访问的(返回后)。我将根据我对代码中发生的情况的解释来回答您。
我可以告诉你很多(乍一看):
引发NameError,因为您试图放入self.Pet1中的全局变量Pet1不存在。
是的,如果Pet1在类之外初始化,当然,在实例化类之前,这件事就可以实现了
# If you wanted just to initialize self.Pet1 then give it a value like: "Pet1", "" or None; inside __init__() constructor.
self.Pet1 = ""
您的类是一个解析器,然后在构造函数中解析您的行,并将值放入atributes。
如果这样做,就不需要其他方法获取参数(而不是self),您可以使用这些属性来访问所需的值。
然后,您将获得类似以下内容:
for line in f:
A = PriceParser(line)
print "Cat1 costs:", A.price("cat1") # Or whatever you want
print "Avg price of all dogs is:", A.PricesMean("dog")
# Use constructor __init__() to do all the job (splitting, putting into attrs, etc.).
# Do not use tons of arguments in methods. What if zoo-shop adds rabbits the next day?
# If you wish to have all kind of pets covered, use one attr with a dictionary to keep values for each, not a new attribute for each pet.
# If you really wish to have an attribute per pet, use an instance scope variable container self.__dict__
# For instance:
def add_doggy (self, dog_name, dog_colour, dog_price):
self.__dict__["dog_"+dog_name] = (dog_colour, dog_price)
# Then the following is possible:
A.add_doggy("Rex", "black", 30):
print "Rex costs:", A.dog_Rex[1]
# But this, and all other methods you can use to do same/similar things are more in field of meta programming for which, I think, you are not ready yet.
请按照我的评论编辑你的问题。
通过示例教程开始学习OOP,尝试做一些严肃的事情,例如使用wxPython编程GUI,这将帮助您掌握其中的诀窍
import numpy as np
inputstr = """\
dog1,cat1,5.00
dog1,cat2,7.00
cat1,dog2,10.00
cat2,dog2,10.00
dog2,dog1,8.00
cat1,cat2,10.00"""
class PriceParser:
def __init__(self, line):
linesplit = line.strip().split(",")
self.Pet1 = linesplit[0]
self.Pet2 = linesplit[1]
self.price = linesplit[2]
self.Pet1short = self.Pet1[0:3]
self.Pet2short = self.Pet2[0:3]
self.combo = self.Pet1short+"__"+self.Pet2short
self.comborev = self.Pet2short+"__"+self.Pet1short
self.PetSame = self.Pet1short+"__"+self.Pet1short
self.dictPetPrices = {}
def PriceIdentifier (self):
if self.Pet1short != self.Pet2short:
if not self.comborev in self.dictPetPrices:
if not self.combo in self.dictPetPrices:
self.dictPetPrices[self.combo]=[]
self.dictPetPrices[self.combo]=[float(self.price)]
else:
self.dictPetPrices[self.comborev].append(float(self.price))
elif self.Pet1short == self.Pet2short:
if not self.PetSame in self.dictPetPrices:
self.dictPetPrices[self.PetSame]=[]
self.dictPetPrices[self.PetSame].append(float(self.price))
return self.dictPetPrices
def PriceSpectrum (self, call_ident=True):
if call_ident: self.PriceIdentifier()
Percentiles = []
for k in self.dictPetPrices.keys():
self.dictPetPrices[k].sort()
a = np.asarray(self.dictPetPrices[k])
Q1 = np.percentile(a, 1)
Q25 = np.percentile(a, 25)
Q50 = np.percentile(a, 50)
Q75 = np.percentile(a, 75)
Q90 = np.percentile(a, 90)
Percentiles.extend([Q1,Q50,Q75,Q90])
return Percentiles
if __name__ == '__main__':
for line in inputstr.split("\n"):
A = PriceParser(line)
print A.PriceIdentifier()
print A.PriceSpectrum()
这将产生以下结果:
{'dog__cat': [5.0]}
[5.0, 5.0, 5.0, 5.0]
{'dog__cat': [7.0]}
[7.0, 7.0, 7.0, 7.0]
{'cat__dog': [10.0]}
[10.0, 10.0, 10.0, 10.0]
{'cat__dog': [10.0]}
[10.0, 10.0, 10.0, 10.0]
{'dog__dog': [8.0]}
[8.0, 8.0, 8.0, 8.0]
{'cat__cat': [10.0]}
[10.0, 10.0, 10.0, 10.0]
请解释一下你想要什么样的结果。
你的意思是制作一个包含所有价格的数组,然后,你必须解析类内的所有输入,或者使用其他结构。
这里只解析一行。
或者,你可以让PriceSpectrum()接受一个参数,一个列表,然后它会累加所有的价格或者类似的东西
如您所见,方法使用属性进行内部通信。
函数的百万个参数是结构化编程的素材。
不要在任何OO中使用这个概念。方法应该只获取请求或提供实例尚不可用的内容所需的参数。
请根据我的密码解释一切。我做错了什么,你希望实现什么。你的问题的沟通是否令人满意,还是你的目标是某种特殊的沟通。
我真的希望这有帮助。至少,现在没有错误。好多了!call_ident是导致调用self.PriceIdentifier()的参数。如果您以前没有手动调用self.PriceIdentifier(),那么可以确保调用了self.PriceIdentifier()。如果您以前确实调用过它,可以说self.PriceSpectrum(0),以避免再次调用它。 如果您希望将一个函数传递给另一个函数,正如我得到的那样,您可以像在C中一样进行传递。Python中的可变对象是通过引用访问的,即指向对象的指针存储在变量中。至少你可以这样看。这就是为什么在将列表传递给函数时必须复制该列表的原因,除非在该函数中更改列表时希望更改原始列表。 因此: 对于方法也可以这样做,因为方法只是带有附加参数self的函数,这是一个
{'dog__cat': [5.0]}
[5.0, 5.0, 5.0, 5.0]
{'dog__cat': [7.0]}
[7.0, 7.0, 7.0, 7.0]
{'cat__dog': [10.0]}
[10.0, 10.0, 10.0, 10.0]
{'cat__dog': [10.0]}
[10.0, 10.0, 10.0, 10.0]
{'dog__dog': [8.0]}
[8.0, 8.0, 8.0, 8.0]
{'cat__cat': [10.0]}
[10.0, 10.0, 10.0, 10.0]
def f (another_func): return another_func()
def g (): print "blah"
f(g)
def callme (func, *args, **kwargs):
print "I will call", func
print "With arguments:", args
print "And keyword arguments:", kwargs
func(*args, **kwargs)
def dateandtime (date, time, zone=None):
print "The date:", date
print "The time:", time
print "Zone:", zone
callme(dateandtime, "01.01.1881. AC", "00:00:00")