3

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?

2 Answers 2

5

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.

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

Comments

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

etc

1 Comment

Please note that calling transform_point(obj) will cause all subsequent calls to transform_point to use the default arg None for x and y.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.