首页 > 解决方案 > 将字符串类型转换为对象时出错

问题描述

这是我使用以下代码面临的问题

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 .................................................. …………

标签: python

解决方案


astr类型,而不是Dot. 因此,没有理由a拥有connections财产。


推荐阅读