GettingItDone
GettingItDone

Reputation: 603

Referencing class constants Python 3

I have a class which has some class constants and functions which make use of the class constants (no instance variables). pylint is returning a problem:

Method should have "self" as the first argument

I am passing the cls reference into the function so to reference the constant. I didn't explicitly reference the class name as it might change (although I could use replace all to make an update).

Example:

def calc_size_string_kilobytes(cls, string: str) -> float:
    return len(string)/cls.BYTES_IN_KILOBYTE

Should this be a static function that explicitly references the class name? Like this:

@staticmethod
def calc_size_string_kilobytes(string: str) -> float:
    return len(string)/ClassName.BYTES_IN_KILOBYTE

What am I missing, I thought it was legitimate to have a class function.

Upvotes: 1

Views: 247

Answers (1)

khelwood
khelwood

Reputation: 59210

The thing you are missing is the @classmethod decorator, which indicates that the first argument the method receives should be the class itself.

Upvotes: 1

Related Questions