0

I know that self is a reference of the class instance, but why could the instance refer to the attribute that has not been declared in the class? I mean, I think it should add three statements a = 0 b = 0 c = 0 in class Triangle but it does't. Also in the next function print_side.

class Triangle:
    def create_triangle(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
        print("The triangle is created")
    def print_side(self):
        print('side a is: ', self.a)
        print('side b is: ', self.b)
        print('side c is: ', self.c)
byhuang1998
  • 377
  • 1
  • 5
  • 25
  • 2
    What do you mean by e.g. `int a`? Python is *dynamically* typed, you don't specify a type for variables or attributes. Note that typically what you should would be implemented by defining `__init__` and `__str__` methods, so that you can't create a `Triangle` *without* setting its side lengths (or `create_triangle` would be a `@classmethod` *returning* an instance). Have a look at e.g. https://docs.python.org/3/tutorial/classes.html. – jonrsharpe Oct 08 '20 at 09:48
  • 1
    This code will fail if you do `Triangle().print_side()`, i.e. you call `print_side` before calling `create_triangle`. That makes this unsafe and rather bad practice/bad code. However, this does work if used as intended. What exactly are you asking about? *Why* you can do it like this? In that case… why not? What expectation of yours does this violate? – deceze Oct 08 '20 at 10:02
  • @deceze thanks for your detailed answer. Actually my question is why `self` could refer attribute `a` when the class has not even declare the attribute? – byhuang1998 Oct 08 '20 at 10:05
  • 1
    Classes don't "declare attributes" in Python. The attribute just gets set, and it either exists or it doesn't. Period. See https://stackoverflow.com/a/12569143/476. – deceze Oct 08 '20 at 10:06
  • Can you please clarify how familiar you are with Python and its concept of classes? Are you aware that Python instance data is well described as ``dict``/hashtables, instead of, say, structs as in C++? The default base type ``object`` can hold arbitrary attributes, without the class having to define what attributes the instance has. A class defining what fields the instance can have is generally known as "slots" (namely via the ``__slots__`` class attribute) but is actually part of a more general topic known as descriptors. – MisterMiyagi Oct 08 '20 at 10:11
  • @deceze Thanks bro, I got it through your link answer. – byhuang1998 Oct 08 '20 at 10:12
  • @MisterMiyagi Yes I'm new in Python. As a result, my intuition is attibutes should be defined before used in function. Your explanation is clear, thanks! – byhuang1998 Oct 08 '20 at 10:15
  • @jonrsharpe Yes bro, I have understood the concept. I should have an init function first so that I can return an object. Thanks for your edit and explanation. – byhuang1998 Oct 08 '20 at 10:19

0 Answers0