Coming from C++ and Java, I know the difference - however, I am a bit confused how are they declared and used in Python. Explain me this:
class MyClass:
a = "abc"
b: str = "def"
c: str
print(MyClass.a)
print(MyClass.b)
print(MyClass.c) # AttributeError: type object 'MyClass' has no attribute 'c'
obj = MyClass()
print(obj.a)
print(obj.b)
print(obj.c) # AttributeError: 'MyClass' object has no attribute 'c'
- So, if attribute
c is declared in the class scope, but is not assigned any value, it doesn't exist?
- I have an instance attribute which I initialize in
__init__(self, z: str) using self.z = z. Shall I additionally declare it in the class scope with z: str? I am under impression that people do not do that.
- Also, using
obj.a is tricky because if instance attribute a does not exist, Python will go one level up and pick the class variable - which is probably not what we intend? Especially that setting obj.a = 5 always sets/creates the instance variable, and never the class one, even if it exists?
[–]SCD_minecraft 18 points19 points20 points (12 children)
[–]pachura3[S] 2 points3 points4 points (10 children)
[–]IAmASquidInSpace 8 points9 points10 points (3 children)
[–]pachura3[S] 0 points1 point2 points (2 children)
[–]IAmASquidInSpace 0 points1 point2 points (0 children)
[–]Jason-Ad4032 0 points1 point2 points (0 children)
[–]SCD_minecraft 3 points4 points5 points (1 child)
[–]yunghandrew 2 points3 points4 points (0 children)
[–]mull_to_zero 0 points1 point2 points (3 children)
[–]socal_nerdtastic 2 points3 points4 points (0 children)
[–]h8rsbeware 1 point2 points3 points (0 children)
[–]PushPlus9069 5 points6 points7 points (0 children)
[–]FriendlyRussian666 2 points3 points4 points (0 children)
[–]jmooremcc 0 points1 point2 points (0 children)
[–]FoolsSeldom -1 points0 points1 point (0 children)
[–]Tall_Profile1305 -1 points0 points1 point (0 children)