On 2018-04-16 18:03, Irv Kalb wrote:
> He gives a demonstration using the following example:
>
> class PartyAnimal():
> x = 0
>
> def party(self):
> self.x = self.x + 1
> print('So far', self.x)
>
> [snip]
>
> But there is something there that seems odd. My understanding is that the "x
> = 0" would be defining a class variable, that can be shared by all
> PartyAnimal objects. But he explains that because x is defined between the
> class statement and the "party" method, that this defines an instance
> variable x. That way, it can be used in the first line of the "party"
> method as self.x to increment itself.
>
> At the end of the video, he creates two objects from the same class, and each
> one gets its own self.x where each correctly starts at zero. Again, I
> expected x to be a class variable (accessible through PartyAnimal.x).
>
> When I want to create an instance variable and to be used later in other
> methods, I do this:
>
> class PartyAnimal():
> def __init__(self):
> self.x = 0
>
> def party(self):
> self.x = self.x + 1
> print('So far', self.x)
>
> [snip]
>
> That is, I would assign the instance variable in the __init__ method. Both
> approaches give the same results.
>
> I'm certainly not trying to argue with Dr. Chuck. I am trying to understand
> his approach, but it's not clear to me why his code works. Specifically, can
> anyone explain how his "x = 0" turns x into an instance variable - while also
> allowing the syntax for a class variable PartyAnimal.x to be used?
>
"self.x = y", whatever self and y are, sets the attribute "x" of the
object "self". Whether "self.x" previously existed does not matter
(ignoring descriptors and the like).
If you access self.x, whether x exists obviously does matter, and
there's a fallback to looking in the class if the instance doesn't have it.
FWIW, I think this business of defining class attributes for things that
are instance-specific a bit daft. Your version strikes me as much more
pythonic.
-- Thomas
--
https://mail.python.org/mailman/listinfo/python-list