Reputation: 1071
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?
Upvotes: 6
Views: 6104
Reputation: 1
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
Upvotes: 0
Reputation: 881665
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.
Upvotes: 3
Reputation: 798666
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.
Upvotes: 2