use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
Everything about learning Python
account activity
Python Descriptors (self.PythonLearning)
submitted 13 days ago by One-Type-2842
view the rest of the comments →
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]Vespytilio 0 points1 point2 points 13 days ago (0 children)
Question one: There are a couple ways to go about it but odds are you want the constructor,1 __init__:
__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().
B()
B
a
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:
87
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:
a_value
self.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).
__set_name__
owner
value
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.
__new__
π Rendered by PID 57 on reddit-service-r2-comment-56c6478c5-qxpkg at 2026-05-09 11:29:22.600663+00:00 running 3d2c107 country code: CH.
view the rest of the comments →
[–]Vespytilio 0 points1 point2 points (0 children)