python,将函数转换为类和对象

2024-06-07 12:32:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我创建了一个完全基于函数和一些全局变量的过程程序,如下所示。我想把程序变成一个面向对象的程序,但我遇到了麻烦,因为我从来没有做过这样的事情。你知道吗

需要遵循的程序是: -函数attack()需要放入一个名为攻击者.py -函数defence()updateVars()smartDefender()需要放在一个文件中卫士.py -main()函数和其余代码(大部分代码)将放在名为经理.py它将是主文件,并将所有内容整合在一起。 -我要上课。你知道吗

我尝试了一系列不同的方法,包括将函数名更改为__init__,然后导入并尝试在中使用它们经理.py. 我还尝试保持函数名相同,只是将函数放在类和import中攻击者.py以及卫士.py进入经理.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()中调用函数的位置,如果这有助于解决问题的话。。你知道吗


Tags: of函数runpy程序defaultifblock
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
"""    

我现在没有足够的时间,但我在这里放置了部分代码,这些代码应该对您有所帮助,稍后我会添加更多

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

相关问题 更多 >

    热门问题