繁体   English   中英

我想在另一个 class 中使用来自 class 的列表,但我无法实现上述目标

[英]I want to use a list from a class in another class, but i am not being able to achieve said goal

所以,我正在做一个项目,我需要在 class 中引用属于另一个 class 的列表,这是我到目前为止得到的:

import pandas as pd
import numpy as np

data = pd.read_excel(r'D:\Coisas fixes\London.connections.xlsx')
df = pd.DataFrame(data, columns=['station1', 'station2'])

data2 = pd.read_excel(r'D:\Coisas fixes\London.stations.xlsx')
df2 = pd.DataFrame(data2, columns=['id', 'name'])


class testing_tests:

    def __init__(self):
        self.edge = []
        self.vector = []
        np_array = df.to_numpy()
        for i in np_array:
            no1, no2 = i
            self.edge.append((no1, no2))
        print(self.edge)


class Edge:

    def __init__(self):
        for i in range(len(testing_tests.edge)):
            self.v1 = df.iloc[i, 0]
            self.v2 = df.iloc[i, 1]

基本上发生的事情是我创建了一个程序来读取 excel 文件,我设法做到了,并将一些值保存在新的 class 中,但我没有想出一种方法来访问其他 ZA2F2ED4F8EBC2CBBD4C21A2 中的列表在 python 控制台上。

c = testing_tests()
-[(11, 163), (11, 212), (49.........
E = Edge()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:/Users/vasco/Downloads/Ze wrk.py", line 26, in __init__
    for i in range(len(testing_tests.edge)):
AttributeError: type object 'testing_tests' has no attribute 'edge'

我放了多个点,因为结果就像 400 个数字。 有谁知道该怎么做? 感谢所有帮助

c = testing_tests()

在这里,您正在创建testing_tests class 的实例,并将该实例分配给c __init__将运行初始化 class 实例,设置self.edge ( c.edge ) 列表。

但是在你的Edge class 里面,你有

for i in range(len(testing_tests.edge)):

在这里,您没有使用您的实例,而是直接引用testing_tests class (不是它的实例)。 class(类似于模板)没有edge属性。 只有 class 的实例有这个。

一种解决方案是在 Edge 中创建一个实例,例如

class Edge:
    def __init__(self):
        self.tt = testing_tests()
        for i in range(len(self.tt.edge)):

顺便说一句,类和它们的实例之间的这种混淆是一个很好的例子,说明为什么使用命名约定可以使代码更具可读性。 如果您将CamelCase用于您的 class 名称,则更容易发现此类问题。 例如

class TestingTests:
    def __init__(self):
        self.edges = []
        np_array = df.to_numpy()
        for i in np_array:
            no1, no2 = i
            self.edges.append((no1, no2))
        print(self.edges)

class Edge:
    def __init__(self):
        self.tt = TestingTests()
        for i in range(len(self.tt.edges)):
            self.v1 = df.iloc[i, 0]
            self.v2 = df.iloc[i, 1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM