Home > other >  Python class attribute and __init__
Python class attribute and __init__

Time:11-19

Eg:
The class Learning (Object) :
Name='property'
Def __init__ (self) :
Target='pro'

As example, defined in the class attribute, directly write the name and in the init target, what's the difference? Bother a great god answers

CodePudding user response:

The name is a class object attribute
The target is __init__ function of the local variable
The self. The target is the instance object attribute

Personal understanding, hope for your help,

CodePudding user response:

Class attribute name attribute is the class learning, one and only one, all of the class of the instance Shared this property, but also learning. The name so call; But under the init target can't
Learning. The target such calls, only after the following calls to declare an instance of this class, use instances to access, (instance can access these two properties),

Then your code a little wrong, lowercase o in front of the Object; Init target cannot write directly, need in the init statement, then use the self to invoke the target (within the definition of method)

I give you the test code, you run the whole see

The class Learning (object) :
Name='property'
Def __init__ (self, target) :
The self. The target='PPP'

Print (Learning. Name)

P1=Learning (' DDD)
Print (p1) name)
Print (p1. Target)

P1. Target='DDD
Print (p1. Target)

P1. Name='TOM'
Print (p1) name)
Print (Learning. Name)

CodePudding user response:

The name is a class attribute, is unique to the Learning class variables, and __init__ constructor, set in when creating an instance variable will be exclusive to instance variables, class attributes can be achieved through inheritance search,
Hypothesis:
A=Learning (3)
So A.t arget equals 3
If you write A.n ame, will get the 'property', but this is not directly from A to b, inside is through inheritance search from class Learning found inside, A themselves don't have the attribute,

PS: __init__ function inside the variable name you want to add the self, the self. The target='target', you can refer to the upstairs
  • Related