讓兩個類進行交互 (getting two classes to interact)


問題描述

讓兩個類進行交互 (getting two classes to interact)

I am having trouble getting two classes to interact. Here is the code for the first class where i am importing file youtest.py:

from youtest import MyTest   

class RunIt(object):

  def __init__(self):
    self.__class__ = MyTest

r = RunIt()
r.iffit()

I am trying to run class MyTest through this class (code below):

from sys import exit

class MyTest(object):

  def death(self):
    exit

  def iffit(self):

    oh_no = raw_input(">")

  print "What is your name?"

  if oh_no == "john":
    print "welcome john"

  else:
    print "game over"
    return 'death'

when i run this i get the following: 

File "youtest.py", line 19     return 'death' SyntaxError: 'return' outside function

Hope this question is clear enough thanks for the help.


參考解法

方法 1:

The lines starting from print "What is your name?" are not indented properly. In python the whitespace is significant.

方法 2:

In Python, this isn't how to subclass.

from youtest import MyTest   

class RunIt(MyTest): pass

r = RunIt()
r.iffit()

Although in this example r = MyTest() would work fine.

Your SyntaxError is triggered by your misuse of white space. Use four spaces for each indentation level, as is standard in Python, so you can clearly see the organization of things. 

You have another problem: return 'death' will not call death, you need to return death() if that's what you want. 

Finally, death() will not do anything with exit, just reference it. You need to do exit().

(by Colin CunninghamSiggyFagf)

參考文件

  1. getting two classes to interact (CC BY-SA 3.0/4.0)

#return #Python #call #interaction #class






相關問題

如果評估的最後一個語句是 If 語句,Ruby 會返回什麼 (What is Returned in Ruby if the Last Statement Evaluated is an If Statement)

將多個參數傳遞給 javascript 並根據兩個參數 + php 循環更新 html 內容 (pass multiple parameters to a javascript and update html content bases on both parameters + php loop)

Loại Không khớp không thể chuyển đổi từ Boolean sang Int (Mảng trong phương thức tùy chỉnh) (Type Mismatch can't convert from Boolean to Int (Arrays in custom method))

C++返回一個帶有私有構造函數的類實例 (C++ return a class instance with private constructor)

ArrayList.isEmpty() 時如何返回值? (How do I return a value when ArrayList.isEmpty()?)

如何將坐標(元組)格式化為字符串? (How can I format a coordinate (tuple) as a string?)

void 類型方法表達式體成員允許非 void 類型的表達式 *如果其他方法* (Void-type method expression-bodied member allows expression of non-void type *if other method*)

paypal動態退貨地址 (paypal dynamic return address)

讓兩個類進行交互 (getting two classes to interact)

在 C++ 中返回“this”? (return "this" in C++?)

Java:枚舉的不同返回類型 (Java: Different return type by enum)

如何檢查函數參數和類型 (How to inspect function arguments and types)







留言討論