6

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?

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

3 Comments

"The class object itself will be instantiated once the class block has exited" Isn't the class object instantiated when the class statement is encountered -- but bound to the class name only on exit of the statement ?
Thanks , Thats what i thought , just wanted to make sure. thanks for clearing it up
@SylvainLeroux The class block is executed with some namespace (a dict-like object provided by the metaclass) to collect class members, then the populated namespace is passed to the metaclass to create the actual class object. See docs.python.org/3/reference/…
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.