简体   繁体   中英

Running Python program from command line

I am using Windows Powershell to import Python file and create instance of one of the class defined with in file as follows:

import random
class RandomWalker:
    def __init__(self):
        self.position = 0

    def walk(self, n):
        self.position = 0
        for i in range(n):
            yield self.position
            self.position += 2*random.randint(0,1) -1

This file is randomWalk.py

So, I run the below command on Python command line:

>>> 

But when I try to create an instance of the class it throws an error:

>>> 

Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'RandomWalker' is not defined

What am I missing? I tried to google, I assume we can create an instance of class on Python command line interface.

You are importing only the module, not the class. With the code you provided try:

import randomWalk

walker = randomWalk.RandomWalker()

or for importing the class directly:

from randomWalk import RandomWalker

walker = RandomWalker()

你应该试试:

walker = randomWalk.RandomWalker()

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