3

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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.