-2
    surface=self.surface
NameError: name 'self' is not defined

how can fix this Python Code is not defined

the code

class Rectangle:
    def __init__(self, longueur=30, largeur=15):
        self.lon = longueur
        self.lar = largeur
        self.nom = "rectangle"
def surface(self):

    return self.lon * self.lar

surface=self.surface

def affichage(self):

    print("rectangle=" + self.nom, "longueur=" + self.lon, "largeur=" + self.lar, "surface=" + self.surface)

class Carre(Rectangle):

    def __init__(self, cote=10):

        Rectangle.__init__(self, cote, cote)

        self.nom = "carre"
r = Rectangle()
print(r)
c = Carre()
print(c)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 2
    You are attempting to access `self` outside the class. It's only defined within the class functions – Jab Dec 01 '22 at 17:30
  • Welcome to Stack Overflow! Please take the [tour]. Obviously the indentation is wrong here, but it's not clear what you're expecting this code to do. If you changed the indentation on `surface = self.surface` and/or `def surface`, it either would still raise an error or wouldn't do anything. Please make a [mre] including minimal code and desired output. For more tips, see [ask]. – wjandrea Dec 01 '22 at 17:35
  • This might be helpful: [I'm getting an IndentationError. How do I fix it?](/q/45621722/4518341) – wjandrea Dec 01 '22 at 17:41

1 Answers1

0

At this line surface=self.surface you're trying to access a variable that does not exist in this scope. self has only been defined within the context of the various functions of your classes, and python doesn't know about it outside of those functions.

If you have an instance of Rectangle called for example rect, you can refer to its member function surface as rect.surface, or you can evaluate that function's value by calling rect.surface().

The key to understanding this is to know that objects can have many names. By convention, within the object we refer to the instance by the name self. Outside of the object, this would be confusing so we use names that tell us what object we're referring to. (Just as you might refer to yourself as "me", but you'd be confused if others used that same word to refer to you!)

Jon Kiparsky
  • 7,499
  • 2
  • 23
  • 38
  • So how do I fix this error can you explain easier – madara_dz Dec 01 '22 at 17:45
  • I have no idea how to fix the error, since you haven't told us what it is you're trying to accomplish. I can tell you why you're getting the result you're getting, but nobody can tell you what to do about it unless you get a lot more clear on what your goal is. – Jon Kiparsky Dec 02 '22 at 06:45