Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Object-Oriented Python (retired) Inheritance Intro to Inheritance

Hara Gopal K
PLUS
Hara Gopal K
Courses Plus Student 10,027 Points

declaring variables outside/before the class

in the following example, the colors list is defined outside the class, i have come across this scenario in procedural way of programming as well, so what's the difference between declaring variable outside the class (in case of oop) / function (in case of procedural programming), would the program react differently ?

import random

COLORS = ['yellow', 'red', 'blue', 'green', 'purple']


class Monster:

    min_hitpoints = 1
    max_hitpoints = 1
    min_experience = 1
    max_experience = 1
    weapon = 'sword'
    sound = 'roar'

1 Answer

The difference is one of scope. If you declare a variable in the module, it is accessible across that module due to being a global variable. If you declare it inside a function/class it is a local variable and is only accessible inside that function or class. If it's in a class it's an attribute of that class and can be access externally through that class.

There are workarounds to all of this, but I've been doing programming for a couple years and have never used them.