Home > Mobile >  How to define a variable of a class as class object in Python
How to define a variable of a class as class object in Python

Time:07-06

I need to define a variable of a class a class object. How can I do it?

if for example I have a class like this :

class A:
  def __init__(self, a, b):
     self.a = a
     self.b = b

and I want to create another class B that have a variable as instance of class A like :

class B:
  def __init__(self, c = A(), d):
     self.c = c
     self.d = d 

How can I do it ? I need to do particular operation or simply declarate c as object of class A when I create the object of class B ?

CodePudding user response:

class B:
  def __init__(self, a, b, d):
     self.c = A(a, b)
     self.d = d

or

class B:
  def __init__(self, c, d):
     self.c = c
     self.d = d

or

class B:
  def __init__(self, d):
     self.c = A(a, b)      # a and b can be values
     self.d = d

CodePudding user response:

What you wrote mostly works:

    def __init__(self, c = A(), d):
        self.c = c

But there's a "gotcha" which you really want to avoid. The A constructor will be evaluated just once, at def time, rather than each time you construct a new B object. That's typically not what a novice coder wants. That signature mentions a mutable default arg, something it's usually best to avoid, if only to save future maintainers from doing some frustrating debugging.

https://dollardhingra.com/blog/python-mutable-default-arguments/

https://towardsdatascience.com/python-pitfall-mutable-default-arguments-9385e8265422

Instead, phrase it this way:

class B:
    def __init__(self, c = None, d):
        self.c = A(1, 2) if c is None else c
        ...

That way the A constructor will be evaluated afresh each time. (Also, it would be good to supply both of A's mandatory arguments.)

  • Related