如何将一个函数的变量值赋予另一个函数?

时间:2019-04-25 08:20:33

标签: python

我正在为练习制作“游戏”。它是一个基本的猜谜游戏,但我只想使游戏具有功能。这是我的问题(例如):

function 1:
   variablaA
   #some other code

function 2:
   variableB
   variableC = varibleA + variableB
   #some other code

我对对象和类的尝试太愚蠢了,但是我不确定我现在知道自己在做什么。

import random
import sys

min = 1
max = 99
guessed_number = random.randint(min, max)

class functions:
    def __init__(game, difficulty, lifes):
        game.difficulty = difficulty
        game.lifes = lifes

    def GameDiff(hardness):
        #Setting game difficulty
        print "Select difficulty : \n 1; Easy \n 2; Medium \n 3; Hard \n"
        difficulty = raw_input()
        if difficulty == "1":
            print "Its just the beginning"
            lifes = 15
        elif difficulty == "2":
            lifes = 10
        elif difficulty == "3":
            lifes = 5
        else:
            print "This isn't an option try again"
            GameDiff(hardness)

    def core(basic):
        #The core of the game
        print "I guessed a number..."
        player_number = int(raw_input("Whats the number I thinking of?"))
        constant = 1
        GameTime = 1
        while GameTime == constant:
            if player_number < guessed_number:
                print "Your number is smaller than my guessed number"
                print "Try to duplicate your number (But maybe Im wrong)"
                player_number = int(raw_input("Make your tip again\n"))

            elif player_number > guessed_number:
                print "Your number is bigger than my guessed number"
                print "Try to half your number (But maybe Im wrong)"
                player_number = int(raw_input("Make your tip again\n"))
            else:
                GameTime = 0
                print "You guessed it! Congratulations"

    def main(self):
        #The whole game only with functions
        functions.GameDiff()
        functions.core()

Function = functions()

Function.main()

1 个答案:

答案 0 :(得分:0)

如果要使用参数定义函数,则需要在调用函数时将数据(参数)传递给函数

示例:

def my_function(name):
  print("my name is " + name)

my_function("Kevin")

在您的情况下,您定义:

def GameDiff(hardness):
def core(basic):

需要参数

当您调用这些函数时,您以错误的方式进行操作:

    def main(self):
        #The whole game only with functions
        functions.GameDiff()
        functions.core()

Function = functions()

您需要传递参数

示例:

        functions.GameDiff(5)
        functions.core(1)

Function = functions(1,5)

注意:优良作法是使用自我而不是游戏

    def __init__(self, difficulty, lifes):
       self.difficulty = difficulty
       self.lifes = lifes
  

它们只是两种不同的类元素:

      init 方法之外的

元素是静态元素。他们属于   上课。它们被所有实例共享。

      init 方法中的

元素是   对象(个体);它们不属于该类。在 init (以及所有其他方法函数)内部创建并以self开头的变量。属于对象实例。