Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a constant object in python

Tags:

python

oop

I defined a class Factor in the file factor.py:

class Factor:
    def __init__(self, var, value):
        self.var = var          # hold variable names
        self.value = value  # hold probability values

For convenience and code cleanliness, I want to define a constant variable and be able to access it as Factor.empty

 empty = Factor([], None)

What is the common way to do this? Should I put in the class definition, or outside? I'm thinking of putting it outside the class definition, but then I wouln't be able to refer to it as Factor.empty then.

like image 395
Dzung Nguyen Avatar asked Feb 27 '26 16:02

Dzung Nguyen


1 Answers

If you want it outside the class definition, just do this:

class Factor:
    ...

Factor.empty = Factor([], None)

But bear in mind, this isn't a "constant". You could easily do something to change the value of empty or its attributes. For example:

Factor.empty = something_else

Or:

Factor.empty.var.append("a value")

So if you pass Factor.empty to any code that manipulates it, you might find it less empty than you wanted.


One solution to that problem is to re-create a new empty Factor each time someone accesses Factor.empty:

class FactorType(type):
    @property
    def empty(cls):
        return Factor([], None)

class Factor(object):
    __metaclass__ = FactorType
    ...

This adds an empty property to the Factor class. You are safe to do what you want with it, as every time you access empty, a new empty Factor is created.

like image 159
Jamie Cockburn Avatar answered Mar 01 '26 05:03

Jamie Cockburn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!