2013-11-28 51 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