Object property setters with “_” and “__” /u/Avivajpeyi Python Education

Can someone explain this behaviour to me? Specifically why ‘__a’ is nnot getting cached.

“`python class Foo():

@property def a(self): if not hasattr(self, “a”): print(“no cached ‘a’, assiging __a”) self.a=’a’ return self.__a

@property def b(self): if not hasattr(self, “_b”): print(“no cached ‘b’, assigning _b”) self._b=’b’ return self._b

f = Foo()

print(“Calling f.a”) print(f”f.a={f.a}”) print(f”f.a={f.a}”) print(“______________”) print(“Calling f.b”) print(f”f.b={f.b}”) print(f”f.b={f.b}”) “`

“` Calling f.a no cached ‘a’, assiging __a f.a=a no cached ‘a’, assiging __a f.a=a


Calling f.b no cached ‘b’, assigning _b f.b=b f.b=b

“`

submitted by /u/Avivajpeyi
[link] [comments]

​r/learnpython Can someone explain this behaviour to me? Specifically why ‘__a’ is nnot getting cached. “`python class Foo(): @property def a(self): if not hasattr(self, “a”): print(“no cached ‘a’, assiging __a”) self.a=’a’ return self.__a @property def b(self): if not hasattr(self, “_b”): print(“no cached ‘b’, assigning _b”) self._b=’b’ return self._b f = Foo() print(“Calling f.a”) print(f”f.a={f.a}”) print(f”f.a={f.a}”) print(“______________”) print(“Calling f.b”) print(f”f.b={f.b}”) print(f”f.b={f.b}”) “` “` Calling f.a no cached ‘a’, assiging __a f.a=a no cached ‘a’, assiging __a f.a=a Calling f.b no cached ‘b’, assigning _b f.b=b f.b=b “` submitted by /u/Avivajpeyi [link] [comments] 

Can someone explain this behaviour to me? Specifically why ‘__a’ is nnot getting cached.

“`python class Foo():

@property def a(self): if not hasattr(self, “a”): print(“no cached ‘a’, assiging __a”) self.a=’a’ return self.__a

@property def b(self): if not hasattr(self, “_b”): print(“no cached ‘b’, assigning _b”) self._b=’b’ return self._b

f = Foo()

print(“Calling f.a”) print(f”f.a={f.a}”) print(f”f.a={f.a}”) print(“______________”) print(“Calling f.b”) print(f”f.b={f.b}”) print(f”f.b={f.b}”) “`

“` Calling f.a no cached ‘a’, assiging __a f.a=a no cached ‘a’, assiging __a f.a=a


Calling f.b no cached ‘b’, assigning _b f.b=b f.b=b

“`

submitted by /u/Avivajpeyi
[link] [comments] 

Leave a Reply

Your email address will not be published. Required fields are marked *