如何在python中访问不同类中任何类的变量和函数

2024-05-23 14:35:14 发布

您现在位置:Python中文网/ 问答频道 /正文

import copy

class Myclass0:
    paperlist=[]
class Myclass1:
    def copy_something(self):
        Paper = Myclass0()
        Flowers = ["Roses","Sunflower","Tulips","Marigold"]
        Paper.paperlist = copy.copy(Flowers)
class Myclass3:
    superlist = []
    Paper = Myclass0()
    print(Paper.paperlist)
    superlist.append(paperlist[0])     

我在编译时遇到一个索引超出范围的错误。请帮助我找到一种方法,在Myclass3中使用类Myclass1函数和属性打印Myclass0纸质列表。您可以更改类体,但所有类都应使用

我在等待你的宝贵努力

谢谢


Tags: importselfdefsomethingclasspapercopysunflower
1条回答
网友
1楼 · 发布于 2024-05-23 14:35:14

也许这个代码片段可以帮助您更好地理解它:

class MyClass0:
    def __init__(self):
        # this is now an attribute of the instance (not the class)
        self.paperlist = []


class MyClass1:

    @staticmethod
    def copy_something(paper):
        # this is a static method (it doesnt rely on the Class (MyClass1) or an instance of it
        flowers = ["Roses", "Sunflower", "Tulips", "Marigold"]
        paper.paperlist = flowers


class Myclass3:
    def __init__(self, paper):
        # when an instance of this class is created an instance of MyClass0
        # must pre passed to its constructor. It then prints out its paperlist
        print(paper.paperlist)


paper = MyClass0()
MyClass1.copy_something(paper)
Myclass3(paper)

相关问题 更多 >