python,将函数更改为类和对象

时间:2012-12-07 14:25:44

标签: python

下面有很多代码,但您不必真正阅读其中的任何代码,您只需要知道函数存在和函数名称。我将首先描述我的问题。

我已经完全基于函数和一些全局变量创建了一个程序程序,如下所示。我想将程序更改为面向对象的程序,但我遇到了麻烦,因为我之前从未做过这样的事情。

需要遵循的程序是: - 需要将函数attack()放入名为attacker.py的文件中 - 需要将函数defence()updateVars()smartDefender()放入文件defender.py中 - main()函数和其余代码(大部分代码)将放在名为manager.py的文件中,该文件将作为主文件并将所有内容组合在一起。 - 我必须使用课程。

我尝试了一系列不同的事情,包括将函数名称更改为__init__,然后导入并尝试在manager.py中使用它们。我还试图保持函数名称相同,只是将函数放在类中,并将attacker.py和defender.py导入manager.py,但似乎没有任何工作......任何和所有的帮助将不胜感激。

虽然我认为你真的不需要描述程序的功能,如果你真的需要一个,我可以做一个简短的,或者你可以查看它here.

任何和所有帮助将不胜感激。

import random

HIGH= 3
MED= 2
LOW= 1

def attack(attackList):

    x= random.uniform(0,1)
    for attackLevel,probability in attackList:
        if x<probability:
            break
        x=x-probability
    return attackLevel





def defence(attackLevel,defendList):

    x= random.uniform(0,1)
    for defendLevel,probability in defendList:
        if x<probability:
            break
        x=x-probability
    return defendLevel





def updateVars(attackLevel,defendLevel,block,hit,run):

    if attackLevel==1:
        printAttackLevel='Low'
    if attackLevel==2:
        printAttackLevel='Medium'
    if attackLevel==3:
        printAttackLevel='High'
    if defendLevel==1:
        printDefendLevel='Low'
    if defendLevel==2:
        printDefendLevel='Medium'
    if defendLevel==3:
        printDefendLevel='High'



    if attackLevel==defendLevel:
        block=block+1
        hit=hit
        run=run+1
    else:
        block=block
        hit=hit+1
        run=run+1

    return block,hit,run,printAttackLevel,printDefendLevel





def smartDefender(defendLevel,attackLevel,smartList):

    for i in smartList:
        if (i==(i+1)==(i+2)):
            defendLevel= attackLevel
            return defendLevel
        else:
            return






def main():

    DEFAULT_PROBABILITY= 0.33
    run=0
    hit=0
    block=0
    smartList=[]


    rounds= int(input("\nPlease enter the number of rounds between 1 and 100:"))
    if rounds<=0 or rounds>100:
        print("\n")
        print("Invalid range. The number of rounds has been set to 10 by DEFAULT_PROBABILITY.")
        rounds=10


    lowAttackProb= float(input("\nPercentage of attacks aimed low(0-100):"))/100
    medAttackProb= float(input("Percentage of attacks aimed medium(0-100):"))/100
    highAttackProb= float(input("Percentage of attacks aimed high(0-100):"))/100
    if lowAttackProb+medAttackProb+highAttackProb !=1.00:
        print("\n")
        print("Invalid entry. The sum of the pecentages must equal 100%. The probability of each level has been set to 33.0% by DEFAULT_PROBABILITY.")
        lowAttackProb=DEFAULT_PROBABILITY
        medAttackProb=DEFAULT_PROBABILITY
        highAttackProb=DEFAULT_PROBABILITY


    print('\nLet The Fighting Begin')
    print('-'*22)


    while  run < rounds:

        lowDefProb= DEFAULT_PROBABILITY
        medDefProb= DEFAULT_PROBABILITY
        highDefProb= DEFAULT_PROBABILITY


        attackList= [(LOW,lowAttackProb),(MED,medAttackProb),(HIGH,highAttackProb)]
        attackLevel= attack(attackList)
        smartList.append(attackLevel)
        defendList=[(LOW,lowDefProb),(MED,medDefProb),(HIGH,highDefProb)]
        defendLevel=defence(attackLevel,defendList)
        block,hit,run,printAttackLevel,printDefendLevel= updateVars(attackLevel,defendLevel,block,hit,run)
        if run>(rounds/2):
            defendLevel=smartDefender(defendLevel,attackLevel,smartList)
            #implement smart mode

        print('%s%2s%s%3s%s%5s%s%3s'% ('\nRound',run,':\t','Attacker:',printAttackLevel,'\t','Defender:',printDefendLevel))


    print("%2s%2d%s%s%2d"% ('\nTotal Hits:',hit,'\t','Total Blocks:',block))
    print('Attacker Proportions:','','','Low:','','',lowAttackProb*100,'%','','','Medium:','','',medAttackProb*100,'%','','','High:','','',highAttackProb*100,'%')
    print('Defender Proportions:','','','Low:','','',lowDefProb*100,'%','','','Medium:','','',medDefProb*100,'%','','','High:','','',highDefProb*100,'%')
    print("\nThank you for using this program, Goodbye!")





main()

我的问题是,我如何能够非常轻松地(不一定有效地)将这些程序性程序转换为使用类和多个文件的面向对象程序。

我认为问题区域将包括在main()中调用函数的位置,如果这有助于解决问题..

2 个答案:

答案 0 :(得分:2)

如果它有帮助......我只是将这个基于类的脚本作为一个例子。

class Car():

    def __init__(self, mileage=0, mpg=10, tank_capacity=5):
        self.mileage = mileage
        self.mpg = mpg
        self.tank_capacity=tank_capacity
        self.tank_level = 0                

    def drive(self, miles):
        gallons_burned = float(miles) / self.mpg
        if self.tank_level < gallons_burned:
            miles_driven = float(self.tank_level) * self.mpg
            self.tank_level = 0
            self.mileage += miles_driven
            print "You ran out of gas after %s miles." % miles_driven
            return
        self.tank_level -= gallons_burned
        self.mileage += miles
        print "You made it to your destination after %s miles." % miles

    def pump_gas(self, gallons):
        self.tank_level += gallons
        if self.tank_level > self.tank_capacity:
            self.tank_level = self.tank_capacity
        print "You now have %s gallons in your tank" % self.tank_level

    def status(self):
        print "Mileage:", self.mileage
        print "Tank level: %s gallons" % self.tank_level

if __name__ == "__main__":
    my_car = Car(mileage=100, mpg=30, tank_capacity=3)
    my_car.pump_gas(4)
    my_car.status()
    my_car.drive(50)
    my_car.status()
    my_car.drive(60)
    my_car.status()

"""
You now have 3 gallons in your tank
Mileage: 100
Tank level: 3 gallons
You made it to your destination after 50 miles.
Mileage: 150
Tank level: 1.33333333333 gallons
You ran out of gas after 40.0 miles.
Mileage: 190.0
Tank level: 0 gallons
"""    

答案 1 :(得分:0)

我现在没有足够的时间,但是我在这里放置了一些应该帮助你的代码,稍后我会添加更多

import random


class Attacker(object):
    def __init__(self, power):
    """In this method you can assign
        variables or perform actions which
        you want to perform on object create"""

        #for example on object create we want
        #to set strenght of attacker
        #so this variable will live and
        #availiable for object whole it's
        #life
        self.power = power

    def attack(self):
    """So attacker must can attack
        for example this method just
        return random int multiple on self.power 
        later we compare value of from defender's
        defend method and decide who is
        winner of round"""

        return random.randint(100) * self.power