ryanjdillon
ryanjdillon

Reputation: 18948

Default to class variables in a python class method?

I am writing a class method that I would like to use class variables if no other values are provided

def transform_point(self, x=self.x, y=self.y):

BUT... that doesn't seems to work:

NameError: name 'self' is not defined

I am getting the feeling there is a more clever way of doing this. What would you do?

Upvotes: 3

Views: 171

Answers (2)

YXD
YXD

Reputation: 32511

def transform_point(self, x=None, y=None):
    if x is None:
        x = self.x
    if y is None:
        y = self.y

etc

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121266

You need to use sentinel values, then replace those with the desired instance attributes. None is a good option:

def transform_point(self, x=None, y=None):
    if x is None:
        x = self.x
    if y is None:
        y = self.y

Note that the function signature is executed only once; you cannot use expressions for default values and expect those to change with each call to the function.

If you have to be able to set x or y to None then you need to use a different, unique singleton value as the default instead. Using an instance of object() is usually a great sentinel in that case:

_sentinel = object()

def transform_point(self, x=_sentinel, y=_sentinel):
    if x is _sentinel:
        x = self.x
    if y is _sentinel:
        y = self.y

and now you can call .transform_point(None, None) too.

Upvotes: 5

Related Questions