Home > other >  How to function in a class variable references
How to function in a class variable references

Time:09-16

The class Testdd () :

Def out (self) :
Global md
Md=100
Print (" out function ")

Def other (self) :
Print (" othoer function ")

Ss=md + 200
Print (ss)

If __name__=="__main__" :
T=Testdd ()
T.o ther ()

Code as above, perform NameError: the name 'md' is not defined
I want the result is the final print out 300,
The variables in the md is in out function that can be directly used in other functions, is there any way to do it,
I checked global said the can, I use the deficiency is not defined, and the way of, thank you

CodePudding user response:

 
Md=100

Def other (self) :
Print (" othoer function ")
Ss=self. Md + 200
Print (ss)

CodePudding user response:

reference 1st floor without a white reply:
 
Md=100

Def other (self) :
Print (" othoer function ")
Ss=self. Md + 200
Print (ss)


You this not ah, I just, for example, want the way from a to define a variable in a function, used in another function

CodePudding user response:

How wrong, global md is super global variables, need to have the md outside of class, so you can modify the md and the global definition didn't have anything to do with you

Whole class space, the outermost variable is called a class attribute, there are three kinds of writing:

Class A:
Md=XXX

Class B:
Def out (self) :
The self. The md=XXX

Class C:
Def __init__ (self) :
The self. The md=XXX


In class scope, attribute is its global variables, in the class of functions, can use the above three methods to use, in the use of any other function are self. XXX

CodePudding user response:

You have to write so can also, method is more, too ugly,
 
The class Testdd () :

Def out (self) :
Globals () [' md]=100
Print (" out function ")

Def other (self) :
Print (" othoer function ")

Ss=md + 200
Print (ss)

If __name__=="__main__" :
T=Testdd ()
T.o ther ()
  • Related