Python Forum
class needs to refer a different class
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
class needs to refer a different class
#10
(Jul-16-2021, 05:56 AM)Skaperen Wrote: i have a class that, during __init__(), detects a situation where a different class, not itself, needs to be provided to the caller. but Python classes don't work by returning a reference to the class. is there a way to substitute an instance of a different class, instead?
I think you are a more experienced programmer than I am but you seem to not want to just try things.
We don't need to see your full project files just some basic classes representing what you are trying to do.
I came up with the following based on your description it may be nothing like what you want but perhaps you can adjust it to give an indication of what you are after.
from dataclasses import dataclass


@dataclass
class AClass:
    situation: bool

    def __new__(cls, situation: bool):
        if situation:
            return DifferentClass(situation)
        return super().__new__(cls)


@dataclass
class DifferentClass:
    situation: bool


a_class = AClass(situation=False)
different_class = AClass(situation=True)
print(a_class)
print(different_class)
Output:
AClass(situation=False) DifferentClass(situation=True)
Reply


Messages In This Thread
RE: class needs to refer a different class - by Yoriz - Jul-18-2021, 02:15 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  is ValueError a class? Skaperen 11 2,636 Mar-29-2023, 02:25 AM
Last Post: Skaperen
  extracting a function/class/method from code Skaperen 5 2,302 Mar-30-2022, 12:13 AM
Last Post: Skaperen
  first class objects Skaperen 0 962 Jan-22-2022, 02:53 AM
Last Post: Skaperen
  returning a different class Skaperen 4 2,144 Oct-20-2021, 12:51 AM
Last Post: Skaperen
  getting my head arounnd __enter__() for my new class Skaperen 5 2,554 Nov-30-2020, 09:46 AM
Last Post: Gribouillis
  find the class for indexed counting Skaperen 4 2,033 Sep-29-2020, 03:26 AM
Last Post: Skaperen
  namespaces when defining a class Skaperen 3 2,146 Jul-03-2020, 06:34 PM
Last Post: Gribouillis
  a file-like class implementation Skaperen 2 2,086 Apr-22-2020, 02:59 AM
Last Post: Skaperen
  making a generator class? Skaperen 2 2,102 Apr-01-2020, 12:34 AM
Last Post: Skaperen
  single-instance class Skaperen 3 2,569 Mar-05-2020, 12:47 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

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