python - 为什么会引发 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 ()
解决方案
考虑到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
;你可以给它起任何名字!
推荐阅读
- excel - 验证文本框条目中的日期格式
- python - 通过 Python 代码登录 SAP GUI 时如何检查错误
- selenium-webdriver - selenium webdriver 在抛出 NoSuchElementException 之前的默认等待时间是多少
- java - OpenJdk 初始启动时间很慢
- java - 如何使用@Path 设置休息网址(获取查看文件的链接)
- javascript - 在 setState() 之后,更新的状态不会作为道具传递给组件
- python - python中的循环没有正确递增
- python - 如何在 TensorFlow 1.13 中检查 TFRecord 文件的结构?
- react-native - 将多个选中的复选框值传递给 React Native 中的 TextInput
- vue.js - 我无法在 vuejs 中使用 v-for 显示来自 API 的数据