How to access static properties in an object in Python

1 Answer

0 votes
class Configuration:
    # Define a private class attribute (acts as a static property)
    # Using a leading underscore indicates it's intended for internal use
    _environment = "production"

    @classmethod
    def get_environment(cls) -> str:
        """Class method to safely access the class attribute."""
        return cls._environment

    @classmethod
    def set_environment(cls, new_env: str) -> None:
        """Class method to safely modify the class attribute."""
        if new_env and new_env.strip():
            cls._environment = new_env


# --- Example Usage ---

if __name__ == "__main__":
    # 1. Accessing the static property via the Class Name (Best Practice)
    print(f"Current Environment: {Configuration.get_environment()}")

    # 2. Modifying the static property via a class method
    Configuration.set_environment("staging")
    print(f"Updated Environment: {Configuration.get_environment()}")



'''
run:

Current Environment: production
Updated Environment: staging

'''

 



answered Oct 31 by avibootz
...