我在Python中遇到这个错误 - [英] I am getting this error in Python-
本文介绍了我在Python中遇到这个错误 - 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
代码 -
code--
import numpy as np
def __init__(self, k = 3, eps = 0.0001):
self.k = k ## number of clusters
self.eps = eps ## threshold to stop `epsilon`
X=np.genfromtxt('D:\\M Tech\\ctech\\my_courses\\ELL784\\Assignment-3\\train_data.csv',delimiter=' ') #loading test data
print(X)
n, d = X.shape
print("n=",n ,"d=",d)
clus=3
mu = X[np.random.choice(n, self.k, False), :]
print(mu)
输出 -
output--
[[ 1.09222171 1.89465052]
[ 1.25575788 -1.59750016]
[ 1.2305203 3.6342979 ]
[ 0.69251878 -0.12405407]]
n= 4 d= 2
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-20-7bd596b4f068> in <module>()
12 print("n=",n ,"d=",d)
13 clus=3
---> 14 mu = X[np.random.choice(n, self.k, False), :]
15 print(mu)
NameError: name 'self' is not defined
我尝试过:
无法找到错误,
我认为需要在_init_函数中纠正一些问题,但那是什么?
plz help。
What I have tried:
not able to find error,
I think something need to be corrected in _init_ function, but what is that ??
plz help.
推荐答案
self
对象仅存在于__ init __
方法。在剩余的代码中,它没有定义。您需要创建一个不同的变量来存储该值。
[edit]
参见 9。类 - Python 3.4.5文档 [ ^ ]。
[/ edit]
Theself
object only exists within the scope of the__init__
method. Within the remaining code it is not defined. You need to create a different variable to store that value.
[edit]
See 9. Classes — Python 3.4.5 documentation[^].
[/edit]
在Python中,__ init__方法用于初始化对象实例(半对等于C ++中的构造函数) 。通过self.k,你说变量k存在于某个对象中。如果你试图在对象外部访问该变量,你可以使用ObjectName.k约定。
如果是您发布的代码,你有一个没有关联类的init方法,所以不确定甚至会调用代码。我很惊讶,实际上并不是一个自动Python错误,因为它似乎不应该是有效的(可能只是被解析器忽略)。
In Python, the __init__ method is used to initialize an object instance (semi-equivalent to a constructor in C++). By "self.k", you're saying that the variable "k" exists within some object. If you'd be trying to access that variable externally to the object, you'd use the ObjectName.k convention.
In the case of the code you posted though, you have an init method with no associated class, so not sure that code will even be called at all. I'm surprised that's not an automatic Python error actually, because it doesn't seem like it should be valid (probably just being ignored by the parser).
这篇关于我在Python中遇到这个错误 - 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文