简体   繁体   English

如何从不同的文件导入具有 Python 中所有功能的 class?

[英]How to import class with all functions in Python from different file?

I created 'class V' in file 'V.py' with some functions, which I want to keep using in other projects, but when I call any of these functions I get an error that the name is not defined.我在文件“V.py”中创建了“V 类”,其中包含一些我想在其他项目中继续使用的函数,但是当我调用这些函数中的任何一个时,我会收到一个错误,即名称未定义。 I tried all solutions that I could find and nothing fixes it.我尝试了所有我能找到的解决方案,但没有任何解决方案。 Hope somebody knows what am I doing wrong..希望有人知道我在做什么错..

class V(object):

    def magnitude(self):
        a=0
        for i in range(len(self)):
            for j in range(len(self[i])):
                a= a + self[i][j] **2
        return sqrt(a)

Calling a function:调用 function:

from V import V
A = np.array([[1,2,3],[4,0,6],[7,8,9]])
print magnitude(A)

Error:错误:

NameError: name 'magnitude' is not defined

Refactor your class method to take a parameter, and create an object of class before accessing the method.重构您的 class 方法以获取参数,并在访问该方法之前创建 class 的 object 。

from math import sqrt


class V(object):

    def magnitude(self, A):
        a = 0
        for i in range(len(A)):
            for j in range(len(A[i])):
                a = a + A[i][j] ** 2
        return sqrt(a)
import numpy as np
from V import V

v = V()
A = np.array([[1,2,3],[4,0,6],[7,8,9]])
print (v.magnitude(A))

This will work.这将起作用。 The reason is you are trying to access class method without creating a class object and passing a parameter inside the method too.原因是您试图访问 class 方法而不创建 class object 并在方法内部传递参数。 self is basically the object on which the method is being called. self基本上是调用该方法的 object。

You should pass magnitude to class, not to method try:您应该将幅度传递给 class,而不是方法尝试:

from V import V
A = np.array([[1,2,3],[4,0,6],[7,8,9]])
m = V(A)
print (V)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM