Home > Backend Development > Python Tutorial > How do variable scopes work within Python classes?

How do variable scopes work within Python classes?

Patricia Arquette
Release: 2024-11-19 08:13:02
Original
405 people have browsed it

How do variable scopes work within Python classes?

Variable Scopes in Python Classes

Scope Variation

In Python classes, variable scope varies based on where they're declared:

  • Class-level variables (outside functions): Accessible to all class functions (public variables).
  • Function-local variables (inside class functions): Restricted to that specific function (within its scope).

self vs. Global Variables

Declaring a variable with self.(variable name) within a class function also makes it accessible to all class functions. However, unlike global variables, these variables are specific to the current instance and do not override class-level variables.

Additional Nuances

  • Single vs. Double Underscore Prefix: Variables beginning with a single underscore (e.g., _variable) are considered protected and should only be accessed within the class. Variables beginning with double underscores (e.g., __variable) are mangled and effectively private.
  • Local Variables: Variables declared within class functions are local to those functions and don't affect the class scope.

Example

Consider the following class:

class Test:
    a = None
    b = None

    def __init__(self, a):
        print(self.a)
        self.a = a
        self._x = 123
        self.__y = 123
        b = 'meow'
Copy after login
  • a and b are class-level variables accessible from any instance.
  • a is overridden by the instance-specific self.a in __init__.
  • _x is protected and not part of the public API.
  • __y is mangled and private to the class.
  • b is a local variable accessible only within __init__.

The above is the detailed content of How do variable scopes work within Python classes?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template