Access instance of a class - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Access instance of a class (/thread-35578.html) |
Access instance of a class - Pavel_47 - Nov-18-2021 Hello, In my project there is a lot of different classes, created in different .py files. To implement some feature I need to dynamically change a property of an instance of some class. To test how to proceed I've tried to reproduced the case in significantly simplified case. Here is 2 files: class_instances_test_v0.py: import weakref class MyClass: _instances = set() def __init__(self, name): self.name = name self._instances.add(weakref.ref(self)) @classmethod def getinstances(cls): dead = set() for ref in cls._instances: obj = ref() if obj is not None: yield obj else: dead.add(ref) cls._instances -= dead a = MyClass("a") b = MyClass("b") c = MyClass("c")class_instances_test_v0_test.py: import class_instances_test_v0.MyClass for obj in MyClass.getinstances(): print(obj.name)Here is error message: Any comments. Thanks. RE: Access instance of a class - Pavel_47 - Nov-18-2021 resolved, it was typo ... Should be ... from class_instances_test_v0 import MyClass Actually it's a little bit more complicated. Due to hierarchy of files/classes I get such error (AAA and BBB names are alternate names - for ease of understanding): In file BBB.py I use such import instruction:form AAA.AAA import AAA RE: Access instance of a class - Gribouillis - Nov-18-2021 Please write sensible code! What is the meaning of from AAA.AAA import AAA RE: Access instance of a class - Pavel_47 - Nov-18-2021 The AAA is the name related to project.Well ... talking in different terms, it looks like this: the class AAA is defined in the file AAA.py . The file AAA.py is located in the project sub-folder AAA .
RE: Access instance of a class - Pavel_47 - Nov-19-2021 Resolved: Instead of from AAA.AAA import AAAuse import AAA.AAAThen in code when the object of class AAA is referenced, use AAA.AAA.AAA RE: Access instance of a class - Gribouillis - Nov-19-2021 There was probably a circular import. It would be best to find it: determine which import statements are executed, in which order. Another workaround could be import AAA.AAA from AAA.AAA import AAA |