【问题标题】:within a class , call x function to return a list value from y function. python [duplicate]在一个类中,调用 x 函数从 y 函数返回一个列表值。蟒蛇[重复]
【发布时间】:2021-08-10 14:26:10
【问题描述】:

主要代码

import matplotlib.pyplot as plt

from refract import random_move

while True:

rw = random_move(5000)
rw.track()
pointsv = list(range(rw.points))
fed = input("you need scatter/ plot: y/n ")
if fed == 'y':
    plt.scatter(rw.xv,rw.yv, c= pointsv ,cmap=plt.cm.Greens, s = 2)
    plt.show()
if fed == 'n':
    plt.plot(rw.xv,rw.yv, c = [0,0.5,0.5], linewidth = 2)
    plt.show()

  

类定义

   class .....................

  from random import choice

  class random_move():
      def __init__(self,points):
    self.xv = [0]
    self.yv = [0]
    self.points= points
    
def track(self):
        xv= getstep()
        yv= getstep()
        
def getstep(self):
    dxv = [0]
    while len(dxv) < self.points:
        xd = choice([1])
        xva = choice([3,4,5,7,8,9])
        xt= xd*xva
        if xt == 0:
            continue
        nx =  dxv[-1]+xt
        dxv.append(nx)
        
    return dxv

最终输出:

  error: 
  ---------------------------------------------------------------------------


    NameError: name 'getstep' is not defined

        

【问题讨论】:

  • 格式损坏很难确定,但您似乎正在尝试将 方法 getstep 作为全局函数调用>.
  • 对不起!我是论坛的新手。在一个类 random_move 下,我创建了两个函数,并从另一个函数调用一个函数来请求一个列表值。之后我将类导入到一个单独的文件中,当我从那里调用函数时,nameError 被抛出到屏幕中

标签: python python-3.x function class


【解决方案1】:

试试看;

def track(self):
        self.xv= self.getstep()
        self.yv= self.getstep()

您必须通过类中的对象或通过类本身传递该类的对象来调用类的方法。在您的情况下,要调用 track 方法,您应该调用 self.getstep()random_move.getstep(an_obj_of_the_class)

【讨论】:

    猜你喜欢
    • 2018-09-04
    • 1970-01-01
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 2014-06-13
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    相关资源
    最近更新 更多