Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Are class attributes equivalent to local variables when inside a method?

In python, I know that looking up a locally scoped variable is significantly faster than looking up a global scoped variable. So:

a = 4
def function()
    for x in range(10000):
        <do something with 'a'>

Is slower than

def function()
    a = 4
    for x in range(10000):
        <do something with 'a'>

So, when I look at a class definition, with an attribute and a method:

class Classy(object):
    def __init__(self, attribute1):
        self.attribute1 = attribute1
        self.attribute2 = 4
    def method(self):
        for x in range(10000):
            <do something with self.attribute1 and self.attribute2>

Is my use of self.attribute more like my first or second function? What about if I sub class Classy, and try to access attribute2 from a method in my sub class?

like image 239
Wilduck Avatar asked Jun 30 '10 15:06

Wilduck


People also ask

What is true about the class attributes?

Class attributes are attributes which are owned by the class itself. They will be shared by all the instances of the class. Therefore they have the same value for every instance. We define class attributes outside all the methods, usually they are placed at the top, right below the class header.

Is attribute and method same in Python?

A variable stored in an instance or class is called an attribute. A function stored in an instance or class is called a method.

What are class attributes in Python?

Class attributes are the variables defined directly in the class that are shared by all objects of the class. Instance attributes are attributes or properties attached to an instance of a class. Instance attributes are defined in the constructor. Defined directly inside a class.

What is the difference between class attributes and instance attributes in python?

Differences Between Class and Instance Attributes The difference is that class attributes are shared by all instances. When you change the value of a class attribute, it will affect all instances that share the same exact value. The attribute of an instance on the other hand is unique to that instance.


1 Answers

Locally scoped variables are fast because the interpreter doesn't need to do a dictionary lookup. It knows at compile-time exactly how many local variables there will be and it creates instructions to access them as an array.

Member attributes require a dictionary lookup, so they execute similar to your first example using globally scoped variables.

For speed, you can do something like:

attribute1 = self.attribute1
# do stuff with attribute1

which shadows attribute1 in a local variable, so only a single dictionary lookup is needed. I wouldn't bother unless I'd done some profiling indicating that a method was a bottleneck, though.

like image 187
Daniel Stutzbach Avatar answered Nov 02 '22 10:11

Daniel Stutzbach