0

I'm trying to reference a variable tha I declared in init as a default value for one of my class methods but i get the NameError: name 'self' is not defined.

class A:
    def __init__(self, f):
        self.c = f

    def b(self, d=self.c):
        pass

how can I do this then?

this is parts of my code

class World:
    def __init__(self, shp):
        self.shape = shp
    def position_finder(self, pos0=(int(self.shape[0]/2), int(self.shape[1]/2)), t_rang=int(self.shape[0]/2), f_rang=0):
        pass

world_shape = (100, 100)

world = World(world_shape)
world.position_finder()
eccentricOrange
  • 876
  • 5
  • 18

2 Answers2

1

What you can do is default to None because it is set at definition time. Then, when the instance method is called you can detect this and if still None set your default. Like this:

class A:
    def __init__(self, f):
        self.c = f

    def b(self, d=None):
        if d is None:
            d = self.c
        return d


a = A(3)
print(a.b())

which prints 3.

theherk
  • 6,954
  • 3
  • 27
  • 52
  • I thought about doing this, but I thought there would be a cleaner way of doing it and I dont know it. tnx. – erfan moradzadeh Apr 05 '22 at 12:51
  • 1
    As far as I know, this is the idiomatic way to do this, and it doesn't conflate class values with instance values. You can't reference values that don't exist yet (instance values) while defining the class. – theherk Apr 05 '22 at 12:52
  • yeah. makes sense, the instance can't exist in class. – erfan moradzadeh Apr 05 '22 at 12:57
-2

b() doesn't know what's going on inside __init__(). So if you want to use a variable across multiple methods, declare it as a property inside the class.

class A:
    c = 0

    def __init__(self):
        self.c = 0  # this line is unnecessary now

    def b(self, d=c):  # "self." is not needed, when defining the arguments
        pass

    # if you use a variable in a function, you must use the self.variable
    def test(self):
        print(self.c)
eccentricOrange
  • 876
  • 5
  • 18