2013-11-28 88 views
0

我想知道如何從我的「公式」類訪問「eq」功能?我所嘗試過的不起作用並返回「未綁定的方法」。謝謝。從Python中的類訪問函數?

class formula(): 
    def eq(): 
     print "What is your Velocity: " 
     v = float(raw_input()) 
     print "What is your Intial Velocity: " 
     u = float(raw_input()) 
     print "What is the time: " 
     t = float(raw_input()) 
     aa = v-u 
     answer = aa/t 
     print "Your Acceleration is: ", answer 

a =formula.eq() 

print a 
+0

[在Python靜態方法](http://stackoverflow.com/questions/735975/static-methods-in- python) – gongzhitaao

+0

爲什麼'公式'中的'eq'完全在?看起來它屬於模塊級別。 – user2357112

回答

3

您需要通過調用它來給eq一個self參數,並創建一個實例formula

class formula(): 
    def eq(self): 
     print "What is your Velocity: " 
     v = float(raw_input()) 
     print "What is your Intial Velocity: " 
     u = float(raw_input()) 
     print "What is the time: " 
     t = float(raw_input()) 
     aa = v-u 
     answer = aa/t 
     print "Your Acceleration is: ", answer 

formula().eq() 

有一個在存儲返回值是沒有意義的,你不回這裏有什麼。

我注意到你實際上並沒有使用你的函數中的任何東西,即需要的一個類。你也可以同樣離開類在這裏,如果你希望把你的配方在一個命名空間,把它放在一個單獨的模塊,而不是不會失去任何東西

def eq(): 
    print "What is your Velocity: " 
    v = float(raw_input()) 
    print "What is your Intial Velocity: " 
    u = float(raw_input()) 
    print "What is the time: " 
    t = float(raw_input()) 
    aa = v-u 
    answer = aa/t 
    print "Your Acceleration is: ", answer 

eq() 

;將def eq()置於文件formula.py中,並將其導入爲import formula。沒有意義在這裏,eq() a staticmethod真的。

0

嘗試:

class formula(): 
def eq(self): 
    print "What is your Velocity: " 
    v = float(raw_input()) 
    print "What is your Intial Velocity: " 
    u = float(raw_input()) 
    print "What is the time: " 
    t = float(raw_input()) 
    aa = v-u 
    answer = aa/t 
    print "Your Acceleration is: ", answer 

a = formula() 
print a.eq() 
+0

touche。沒有抓住它。 – hyleaus

+0

您的縮進現已關閉。注意'formula()。eq()'返回'None'; 'print'在這裏很沒用。 –

1

使它像一個靜態方法

class formula(): 
    @staticmethod 
    def eq(): 
     v = float(raw_input("What is your Velocity: ")) 
     u = float(raw_input("What is your Intial Velocity: ")) 
     t = float(raw_input("What is the time: ")) 
     aa = v - u 
     answer = aa/t 
     print "Your Acceleration is: ", answer 
     return answer 

a = formula.eq() 

print a