【发布时间】:2019-12-18 16:33:55
【问题描述】:
我有以下代码:
import matplotlib.pyplot as plt ### imports plotting
import numpy as np
import pandas as pd
class Population:
def __init__(self,name,population):
self.name = name
self.population = population
self.conservative = self.population * 48/100
self.labour = self.population * 30/100
self.libDem = self.population * 12/100
self.green = self.population * 5/100
self.brexit = self.population * 3/100
self.others = self.population * 2/100
def distribution(self):
print(self.conservative)
print(self.labour)
print(self.libDem)
print(self.brexit)
print(self.others)
def rulingParty(self):
parties = {"Conservative":self.conservative,"Labour":self.labour,"LibDem":self.libDem,"Green":self.green,"Brexit":self.brexit,"Other":self.others}
return max(parties, key=parties.get)
def addCon(self,amount, Lab=1/5,LD=1/5,GRN=1/5,BXT=1/5,Others=1/5):
self.conservative += amount
self.labour += -amount * Lab
self.libDem += -amount * LD
self.green += -amount * GRN
self.brexit += -amount * BXT
self.others += -amount * Others
def addLab(self,amount, Con=1/5,LD=1/5,GRN=1/5,BXT=1/5,Others=1/5):
self.labour += amount
self.conservative += -amount * Con
self.libDem += -amount * LD
self.green += -amount * GRN
self.brexit += -amount * BXT
self.others += -amount * Others
def addLD(self,amount, Con=1/5,Lab=1/5,GRN=1/5,BXT=1/5,Others=1/5):
self.libDem += amount
self.conservative += -amount * Con
self.labour += -amount * Lab
self.green += -amount * GRN
self.brexit += -amount * BXT
self.others += -amount * Others
def addGRN(self,amount, Con=1/5,Lab=1/5,LD=1/5,BXT=1/5,Others=1/5):
self.green += amount
self.conservative += -amount * Con
self.labour += -amount * Lab
self.libDem += -amount * LD
self.brexit += -amount * BXT
self.others += -amount * Others
def addBXT(self,amount, Con=1/5,Lab=1/5,LD=1/5,GRN=1/5,Others=1/5):
self.brexit += amount
self.conservative += -amount * Con
self.labour += -amount * Lab
self.libDem += -amount * LD
self.green += -amount * GRN
self.others += -amount * Others
def addOthers(self,amount, Con=1/5,Lab=1/5,LD=1/5,GRN=1/5,BXT=1/5):
self.others += amount
self.conservative += -amount * Con
self.labour += -amount * Lab
self.libDem += -amount * LD
self.green += -amount * GRN
self.brexit += -amount * BXT
c = Population("UK",100000)
d = [c.conservative,c.labour,c.libDem,c.green,c.brexit,c.others]
while not c.rulingParty()=="Labour":
c.addCon(-1000)
d = np.vstack((d,[c.conservative,c.labour,c.libDem,c.green,c.brexit,c.others]))
print(d)
print(np.shape(d)[0])
需要注意的是,这只是我为了提高我的 Python 技能而进行的一项练习,而不是任何形式的政治模拟。我的问题是,有什么办法可以减少 addCon()、addLab() 等函数中重复行的数量,因为它们都有很多相同的代码。
任何反馈将不胜感激 你的,
【问题讨论】:
-
您可以创建一个字典,其中政党名称作为键,投票作为值。唯一的 add 方法将名称作为参数。然后你遍历 dict 并为给定名称添加,为其他名称减去(还需要一些更多细节)。
-
你能解释一下这个程序是做什么的吗?这也可能属于 Code Review,而不是这里。
-
在
addOthers,你为什么要+= -amount * _?为什么不-= amount * _?
标签: python python-3.x function class shortcut