【问题标题】:Python coding error as it canot defined after i make defPython 编码错误,因为它在我制作 def 后无法定义
【发布时间】:2022-11-18 18:35:53
【问题描述】:

我做了自我进口,但它显示

NameError: name 'self' is not defined
#implementation
class KMeans:
    def __init__(self, n_cluster=8, max_iter=300):
        self.n_cluster = n_cluster
        self.max_iter = max_iter
        
# Randomly select centroid start points, uniformly distributed across the domain of the dataset
min_, max_ = np.min(X_train, axis=0), np.max(X_train, axis=0)
self.centroids = [uniform(min_, max_) for _ in range(self.n_clusters)]

但显示

NameError                                 Traceback (most recent call last)
Input In [50], in <cell line: 9>()
      7 # Randomly select centroid start points, uniformly distributed across the domain of the dataset
      8 min_, max_ = np.min(X_train, axis=0), np.max(X_train, axis=0)
----> 9 self.centroids = [uniform(min_, max_) for _ in range(self.n_clusters)]

NameError: name 'self' is not defined

【问题讨论】:

  • 您的第 8 行和第 9 行是您的 init 的一部分还是应该存在于它之外?如果它需要存在于它之外,则不能在类外使用关键字 self 这种方式。
  • 总是写尽可能多的细节!例如,您使用的是哪个版本或平台、您的操作系统、您想要实现的目标以及遇到困难的地方。
  • @Greymanic wdym 是吗?可以显示吗?
  • @pL3B 的回答涵盖了我的要求。

标签: python nameerror


【解决方案1】:

您应该了解更多关于 Python 中的 OOP 的知识(例如here

self 是对该类当前实例的引用。所以它只能在实例方法内部使用。

您正试图在没有对象本身的情况下访问对象的引用。

您应该将函数定义为类的方法,然后初始化一些实例。之后,您将能够访问它的方法。

更新了一些方法示例:


from random import uniform

import numpy as np


class KMeans:
    def __init__(self, n_cluster=8, max_iter=300):
        self.n_cluster = n_cluster
        self.max_iter = max_iter

    def get_centroids(self, x_train):
        # Randomly select centroid start points, uniformly distributed across the domain of the dataset
        min_, max_ = np.min(x_train, axis=0), np.max(x_train, axis=0)
        self.centroids = [uniform(min_, max_) for _ in range(self.n_cluster)]
        return self.centroids

some_object = KMeans()
some_object.get_centroids([1, 2, 3])
print(some_object.centroids)

你想做这样的事情吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多