1

When creating a new instance (say A) of a class, I want an instance (say B) of another class to be an optional argument of the constructor. If B is given as an argument, then I want the constructor of A to specify that B belongs to A. If not given as an argument, I want my constructor to create a NEW instance (say C) of the same class as where B belong to and specify that this new instance belongs to A.

More specifically, I'm working on an arrival process for a hospital. Arrivals happen according to a stochastic process. I want it to be possible to specify whether an arrival event is regarding an already existing customer (in this case, I should give it as an argument) or that it is going to be a NEW customer, in which case my arrival constructor should create a new instance of customer.

9
  • why should the class B care if the customer is new or existing? if it represents a customer that should be sufficient, and B can have an attribute indicating whether or not it is a new customer Commented Jun 8, 2019 at 12:14
  • Class B, doesn't care, A does. Commented Jun 8, 2019 at 12:15
  • so have some attribute on B that indicates if it's new and you can have A check for that with a method, I think you're making this more complicated than it needs to be Commented Jun 8, 2019 at 12:18
  • can't you just make B a member of A? Commented Jun 8, 2019 at 12:20
  • 1
    I still believe my solution is viable. let me post the code snippet and let me know what you think. If it's not what you meant, i'll just delete it Commented Jun 8, 2019 at 12:33

2 Answers 2

1
class A:
    def __init__(self, b=None):
        if b is None:
            self.b = B()
        else:
            self.b = b
Sign up to request clarification or add additional context in comments.

3 Comments

doesn't he want also check if its known or not?
If no argument is passed to A, it's not known. Otherwise it is.
@user8426627, no this is perfectly fine.
0

Arrivals happen according to a stochastic process. I want it to be possible to specify whether an arrival event is regarding an already existing customer (in this case, I should give it as an argument) or that it is going to be a NEW customer, in which case my arrival constructor should create a new instance of customer.

it is just usage of dict and setdefault:

customers = {}

for co in all_customers:

known_customer = customers.setdefault(hash(co), customer(co))

or if you do want to have it as constructor:

class arrival:

known_cos = {}# quasi static

def __init__(self, co)

  self.customer = known_cos.setdefault(hash(co) , customer(co))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.