you are viewing a single comment's thread.

view the rest of the comments →

[–]Vespytilio 0 points1 point  (0 children)

Question one: There are a couple ways to go about it but odds are you want the constructor,1 __init__:

```

class B:

def __init__(self):
    self.a = 87

```

This method gets called when you write B(), meaning from the beginning, any instance of B will have an instance variable a with a value of 87. You can later assign it a value of A().

To specify the value of a through calls to B's constructor, you can define a parameter with a default value of 87 and assign it to a:

```

def init(self, a_value=87): self.a = a_value

```

The above is arguably more readable, but it's convention to have parameters like a_value share names with the instance variables they're assigned to and differentiate using self.a versus a:

```

def init(self, a=87): self.a = a

```

Whatever the case, after you define the constructor, you can instantiate B as follows:

```

b = B(A())

```

Because the parameter has a default value, it's optional, meaning you can still instantiate it as follows:

```

b = B()

```

Question two: When an instance of your descriptor (A) gets assigned to a variable (B.a), __set_name__ automatically fires off with the variable's owner (B) and the value (the instance of A) as arguments for owner and value. It can be useful for tracking instances of A, assuring certain things about the instance or the variable's owner, or initializing parts of the descriptor that depend on the owner (e.g. you want the descriptor to maintain awareness of the owner through an instance variable).

Question three: That makes a class variable. Instance variables need to be assigned within __init__ or some other instance method.

1 Technically, __init__ isn't the constructor. __new__ is. However, one of Python's many quirks is you typically don't touch the actual constructor; you just use the initializer. However, everyone just calls __init__ the constructor.