python - 将字符串类型转换为对象时出错
问题描述
这是我使用以下代码面临的问题
class Dot:
def __init__(self, connections, name):
self.name = name
self.connections = connections
self.availalbe = True
return
def create_dot(i):
for n in range(i):
name = "dot" + str(n)
globals()[name] = Dot(0, name)
print("Created " + name)
def join_dot(a,b):
if a.connections == 3:
print(a.name + " is unavailable ")
a.available = False
elif b.connections == 3:
print(a.name + " is unavailable ")
b.available = False
else:
a.connections += 1
b.connections += 1
print("dots joined")
create_dot(2)
if a.connections == 3:
print(a.name + " is unavailable ")
a.available = False
elif b.connections == 3:
print(a.name + " is unavailable ")
b.available = False
dotcount = int(input("Initial Dots: "))
create_dot(dotcount)
while True:
a = input("Enter Dot Name: ")
b = input("Enter Dot Name: ")
join_dot(a,b)
这是它输出的错误
Traceback (most recent call last):
File "C:/Users/PatrickSilveira/OneDrive - mail.ccsf.edu/Google Drive/Programming/sprouts.py", line 43, in <module>
join_dot(a,b)
File "C:/Users/PatrickSilveira/OneDrive - mail.ccsf.edu/Google Drive/Programming/sprouts.py", line 18, in join_dot
if a.connections == 3:
AttributeError: 'str' object has no attribute 'connections'
我相信它与 str 和“实例”类型有些相关。我该如何解决这个问题?蟒蛇 3.7 .................................................. …………
解决方案
您a
的str
类型,而不是Dot
. 因此,没有理由a
拥有connections
财产。
推荐阅读
- python - 执行蒙特卡罗方法以找到 f 的最小值
- javascript - 无法在 Javascript 中拆分字符串
- ruby-on-rails - 如何为 ios “构建 Turbolinks.framework”?
- asp.net-web-api - 如何在 ASP API 中将参数从 JS 传递给 Controller
- php - 使用内置 PHP 服务器为 Slim 应用程序 v3 提供静态文件
- macos - 运行私有 docker 映像时出错:standard_init_linux.go:207: exec 用户进程导致“exec 格式错误”
- reactjs - 带有按钮的 React Native FlatList 过滤器
- javascript - 将整数上的千数替换为 0
- python - 我可以改进这个 django 模型结构吗?
- c++ - 模板模板参数替换失败