开发者

Why can I write some things out-of-order in python but not others?

开发者 https://www.devze.com 2023-03-05 20:53 出处:网络
Please have a look below: a = 5 print a + b b = 4 When I try to run the code above, it gives an error: Traceback (most recent call last):

Please have a look below:

a = 5
print a + b
b = 4

When I try to run the code above, it gives an error: Traceback (most recent call last): File "C:/Users/user/Documents/modules/ab.py", line 2, in print a + b NameError: name 'b' is not defined

Ok. a + b is called before b is defined. That means Python runs the code in order, starts from top to down. But, how about this one:

class Data:
    def _开发者_开发问答_init__(self):
        self.debug_level = 9
        self.assign = [0, 0, 0, 0]
        self.days = 0
    def create_days(self, startTime, endTime):

        res = 0
        try:
          if self.final_days < self.maximum_days:

Above, self.final_days and self.maximum_days are not defined yet either, but it does not give any errors. What is the logic behind it?

Best regards,


You're not actually "running" the code yet. In your example, all you have is a method declaration inside the Data class. In it, Python will not check for the existence of class fields because they may be set at another time, in some other method (Python's classes are malleable in that sense).

If you try to run your create_days method in a new instance of the Data class without setting the values for those fields beforehand, you'll get an error.


It doesn't give any errors because the attributes are not accessed when the class is defined. As soon as you call create_days() you'll have a problem :D


The body of a function is evaluated only when it is called, not when it is defined.


References are only looked up when the code is run. You can put whatever names you like in the create_days() method, and none will be checked until the line containing them is executed.


If you actually executed it, you would get AttributeError: Data instance has no attribute 'final_days'

To reproduce this:

x = Data()
x.create_days(1,2)

also, you have a try block. I assume this is an excerpt from some other code. The try block is probably swallowing the exception.


Python is an interpreted language, unlike c++ it is not compiled so the body of a function isn't evaluated until it is called.

0

精彩评论

暂无评论...
验证码 换一张
取 消