0

I've been learning about about C++ in college and one thing that interests me is the ability to create a shared header file so that all the cpp files can access the objects within. I was wondering if there is some way to do the same thing in python with variables and constants? I only know how to import and use the functions or classes in other py files.

LuminousNutria
  • 1,883
  • 2
  • 18
  • 44

2 Answers2

3

First, if you've ever used sys.argv or os.sep, you've already used another module's variables and constants.

Because the way you share variables and constants is exactly the same way you share functions and classes.

In fact, functions, classes, variables, constants—they're all just module-global variables as far as Python is concerned. They may have values of different types, but they're the same kind of variable.

So, let's say you write this module:

# spam.py
cheese = ['Gouda', 'Edam']
def breakfast():
    print(cheese[-1])

If you import spam, you can use cheese, exactly the same way you use eggs:

import spam

# call a function
spam.eggs()

# access a variable
print(spam.cheese)

# mutate a variable's value
spam.cheese.append('Leyden')
spam.eggs() # now it prints Leyden instead of Edam

# even rebind a variable
spam.cheese = (1, 2, 3, 4)
spam.eggs() # now it prints 4

# even rebind a function
spam.eggs = lambda: print('monkeypatched')
spam.eggs()

C++ header files are really just a poor man's modules. Not every language is as flexible as Python, but almost every language from Ruby to Rust has some kind of real module system; only C++ (and C) requires you to fake it by having code that gets included into a bunch of different files at compile time.

abarnert
  • 354,177
  • 51
  • 601
  • 671
  • C++20 now also supports [modules](https://en.cppreference.com/w/cpp/language/modules). – 303 Mar 16 '22 at 01:11
0

If you are just looking to make function definitions, then this post may answer your question:

Python: How to import other Python files

Then you can define a function as per here:

https://www.tutorialspoint.com/python/python_functions.htm

Or if you are looking to make a class:

https://docs.python.org/3/tutorial/classes.html

You can look at example 3.9.5 in the previous link in order to understand how to create a shared variable among different object instances.

Free Url
  • 1,836
  • 2
  • 15
  • 28