Understanding How Attributes Are Declared Outside the Constructor

Asked 1 years ago, Updated 1 years ago, 325 views

What is the difference between Python 3 where the attribute is declared outside and inside the constructor (_init__ method)?Please tell me where Python's documentation is located.

class Something:
    a="<- This attribute and "

    def__init__(self):
        self.b="<- Different handling of this attribute."

python class

2023-01-29 16:23

2 Answers

For example, the code below is

class Something:
    a="<- This attribute and "

    def__init__(self):
        self.b="<- Different handling of this attribute."
        
print(Something.a)
print(Something.b)b)
        
sample=Something()
print(sample.a)
print(sample.b)

print(Something.b)The is an error (AttributeError: type object 'Something' has no attribute 'b').The print(Something.a) in the previous line prints <- This attribute and .
The b of the Something class could not be accessed without creating an instance, but a could be accessed without creating an instance.

If Kunif reads the links in the comments and tries various things himself, it will deepen your understanding.


2023-01-29 21:09

In Kunif, we were able to find Python official document, The answer to this question was found.Thank you to everyone who responded.


2023-01-29 21:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.