简体   繁体   中英

Does the order of variables and functions matter in Class (Python)

When defining variables and functions within a class in python 3.x does it matter in which order you define variables and functions?

Is class code pre-complied before you would call the class in main?

By default, all names defined in the block of code right within the class statement become keys in a dict (that's passed to the metaclass to actually instantiate the class when said block is all done). In Python 3 you can change that (the metaclass can tell Python to use another mapping, such as an OrderedDict , if it needs to make definition order significant), but that's not the default.

The order of class attributes does not matter except in specific cases (eg properties when using decorator notation for the accessors). The class object itself will be instantiated once the class block has exited.

It doesn't matter in which order variables and functions are defined in Class in Python .

For example, there is "Text" class as shown below then it works properly displaying "Hello World" :

class Text:
    text1 = "Hello"
    
    def __init__(self, text2):
        self.text2 = text2            
   
    def helloWorld(self):
        return self.text1 + " " + self.text2
       
    def display(self):    
        print(self.helloWorld())
        
text = Text("World")
text.display() # "Hello World" is displayed

Next, I turned the class attributes upside down as shown below then it still works properly displaying "Hello World" :

class Text:
    def display(self):    
        print(self.helloWorld())
   
    def helloWorld(self):
        return self.text1 + " " + self.text2
        
    def __init__(self, text2):
        self.text2 = text2
        
    text1 = "Hello"
        
text = Text("World")
text.display() # "Hello World" is displayed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM