首页 > 解决方案 > 为什么会引发 NameError

问题描述

我在理解面向对象编程方面遇到了一个问题。为什么我得到:

NameError:名称“硬币”未定义?

你能解释一下类和对象在这个程序中是如何工作的吗?我不明白为什么我们应该传递 self 参数。

import random  # The Coin class simulates a coin that can  # be flipped.
class Coin():
    # The _ _init_ _ method initializes the  # _ _sideup data attribute with ‘Heads’.
    def __init__(self):
        self.__sideup = 'Heads'

    # The toss method generates a random number
    # in the range of 0 through 1. If the number
    # is 0, then sideup is set to 'Heads'. # Otherwise, sideup is set to 'Tails'.
    def toss(self):
        if random.randint (0, 1) == 0:
            self.__sideup = 'Heads'
        else:
            self.__sideup = 'Tails'  # The get_sideup method returns the value  # referenced by sideup.

    def get_sideup(self):
        return self.__sideup
        # The main function. 32

    def main():  # Create an object from the Coin class.
        my_coin = Coin()  # Display the side of the coin that is facing up.
        print ('This side is up:', my_coin.get_sideup ())  # Toss the coin.
        print ('I am going to toss the coin ten times:')
        for count in range (10):
            my_coin.toss ()
            print (my_coin.get_sideup ())
            # Call the main function.

    main ()

标签: python

解决方案


考虑到NameError

import random  # The Coin class simulates a coin that can  # be flipped.
class Coin():
    # The _ _init_ _ method initializes the  # _ _sideup data attribute with ‘Heads’.
    def __init__(self):
        self.__sideup = 'Heads'

    # The toss method generates a random number
    # in the range of 0 through 1. If the number
    # is 0, then sideup is set to 'Heads'. # Otherwise, sideup is set to 'Tails'.
    def toss(self):
        if random.randint (0, 1) == 0:
            self.__sideup = 'Heads'
        else:
            self.__sideup = 'Tails'  # The get_sideup method returns the value  # referenced by sideup.

    def get_sideup(self):
        return self.__sideup
        # The main function. 32

def main():  # Create an object from the Coin class.
    my_coin = Coin()  # Display the side of the coin that is facing up.
    print ('This side is up:', my_coin.get_sideup ())  # Toss the coin.
    print ('I am going to toss the coin ten times:')
    for count in range (10):
        my_coin.toss ()
        print (my_coin.get_sideup ())
        # Call the main function.

main ()

请注意主函数定义是如何取消缩进的。你把它作为你课堂的一部分。此外,函数调用main()需要取消缩进到同一级别。

至于你关于 OOP 和self-keyword 的问题,我建议你看看这个问题文档

简而言之:类方法要能够修改对象的属性,就需要知道这些属性属于哪个对象。它需要引用它适用的对象。self是这个参考。它告诉对象:“这是关于我的!”。有趣的事实:你不需要调用它self;你可以给它起任何名字!


推荐阅读