Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Access instance of a class
#1
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:
[Image: class-instances-issue.jpg]

Any comments.
Thanks.
Reply


Messages In This Thread
Access instance of a class - by Pavel_47 - Nov-18-2021, 03:28 PM
RE: Access instance of a class - by Pavel_47 - Nov-18-2021, 03:40 PM
RE: Access instance of a class - by Gribouillis - Nov-18-2021, 04:49 PM
RE: Access instance of a class - by Pavel_47 - Nov-18-2021, 04:56 PM
RE: Access instance of a class - by Pavel_47 - Nov-19-2021, 09:38 AM
RE: Access instance of a class - by Gribouillis - Nov-19-2021, 10:05 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How can I access objects or widgets from one class in another class? Konstantin23 3 1,084 Aug-05-2023, 08:13 PM
Last Post: Konstantin23
  [Solved] Novice question to OOP: can a method of class A access attributes of class B BigMan 1 1,356 Mar-14-2022, 11:21 PM
Last Post: deanhystad
  dict class override: how access parent values? Andrey 1 1,686 Mar-06-2022, 10:49 PM
Last Post: deanhystad
  access share attributed among several class methods drSlump 0 1,085 Nov-18-2021, 03:02 PM
Last Post: drSlump
  Class Instance angus1964 4 2,497 Jun-22-2021, 08:50 AM
Last Post: angus1964
  Can we access instance variable of parent class in child class using inheritance akdube 3 14,049 Nov-13-2020, 03:43 AM
Last Post: SalsaBeanDip
  Trying to access next element using Generator(yield) in a Class omm 2 2,026 Oct-19-2020, 03:36 PM
Last Post: omm
  Issue referencing new instance from other class nanok66 3 2,265 Jul-31-2020, 02:07 AM
Last Post: nanok66
  Class variable / instance variable ifigazsi 9 4,420 Jul-28-2020, 11:40 AM
Last Post: buran
  How to access class variable? instances vs class drSlump 5 3,409 Dec-11-2019, 06:26 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020