nurabha
nurabha

Reputation: 1212

How to create constant C like struct objects under a namespace in Python

I want to create constant objects of a class that I can use again and again in other classes and functions

# Simple C like struct
class data:
  def __init__(self,a,b)
    self.a = a
    self.b = b

# Constant objects in a namespace ??
class DATA_CONSTANTS:
  DATA1 = data(0,0)
  DATA2 = data(3,5)
  DATA3 = data(43, 23)

If I now want to use DATA_CONSTANTS.DATA1, will it be created on first call or everytime I refer to this object ?

What I am looking for is something like in C++ where you create constant objects in a global or given namespace that can be reused as a constant object with fully qualified name say DATA_CONSTANTS::DATA1 or DATA_CONSTANTS::DATA2 etc.

However I am not sure what I am doing above is a pythonic way to accomplish the same in Python. Is this correct ?

Upvotes: 0

Views: 763

Answers (1)

Aplet123
Aplet123

Reputation: 35560

Variables declared in the upper level of a class are class variables, and are only created once at the site that they're declared, then they remain constants. You can see this for yourself:

def calc_value():
    print("computed the value")
    return 1

class Foo:
    my_var = calc_value()

print(Foo.my_var + Foo.my_var)
# prints "computed the value" then 2

Upvotes: 1

Related Questions