0

Is there any possibility to use internal instance attributes in the signature of a class in Python3? Or if not, what would be the pythonic way to achieve the same effect. What I am thinking of is a signature like this:

  1 class C:
  2     def __init__(self, a=self._b):
  3         self._b = 1
  4         self.a = a

so that I can have a default for a based on some internal attribute _b.

2
  • Can _b be a (logically constant) class attribute? Otherwise, there's no good answer (just use a sentinel value like None as the default). Commented Oct 9, 2022 at 15:25
  • Default value of None & check for that inside the method Commented Oct 9, 2022 at 15:25

1 Answer 1

1

Specify the default as a class variable, and use that as the default in both places:

class C:
    default_a = 1

    def __init__(self, a=default_a):
        self._b = self.default_a
        self.a = a
Sign up to request clarification or add additional context in comments.

2 Comments

ugh, you're right, OP's code confused me as to the actual intent. Rewrote with a class variable.
either way, default_a will be faulty in this way: if it is changed in the class after it is created, the default value in __init__ will remain the previous one, and not be affected by the change. The correct thing to do is use a sentinel value (such as None) as the default argument, and assign the class attr to the instance attr based on whether another value was passed or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.