简体   繁体   中英

Why am I getting NoneType?

I'm trying to write a piece of code that generates a random walk for a scatterplot in pyplot, but keeping getting error: TypeError: object of type 'NoneType' has no len()

from random import choice

class RandomWalk:
    def __init__(self, num_points=5000):
        self.num_points = num_points
        self.x_values = [0]
        self.y_values = [0]

   def get_step(self):
       step = (choice([x for x in range(20)])) * (choice([1, -1]))
       return step

   def fill_walk(self):
       while len(self.x_values) < self.num_points:
           x_step = self.get_step()
           y_step = self.get_step()

           if x_step == 0 and y_step == 0:
               continue

           self.x_values = self.x_values.append((self.x_values[-1] + x_step))
           self.y_values = self.y_values.append((self.y_values[-1] + y_step))

And this is the plot code:

rw = RandomWalk(5_000)
rw.fill_walk()

plt.style.use('classic')
fix, ax = plt.subplots(figsize=(15, 9))
point_numbers = range(rw.num_points)
ax.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.rainbow, edgecolors='none', s=5)
ax.scatter(0, 0, c='green', edgecolors='none', s=100)
ax.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100)
plt.show()

For some reason self.x_values is not being passed, and I get the TypeError for this line:

    while len(self.x_values) < self.num_points:

Any idea why it's not being passed?

self.x_values = self.x_values.append(...)

问题出在上面的行中 - append只返回 None

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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