Why equal to “self.angle” instead of just “angle”?

Why do I need to set self.angle1, self.angle2, and self.angle3 equal to “self.angle” instead of just “angle”?

Inheritance

It has to do with converting the class variable to an instance attribute. All instances of Equilateral inherit the class variable and can treat it as an attribute. The instances don’t have an angle variable; they have a self.angle attribute, which can then be assigned to the three instance attributes.

Sorry for reviving this topic, but I wanted to clarify something. I actually did not understand your initial explanation so I tested self.angle1 = angle and it gave me a “NameError: global name ‘angle’ is not defined”.

Is the reason we do self.angle1 = angle because the def init() method does not have access to the angle variable? Because even if angle is a class/member variable, technically speaking, init() is not considered an instance object, rather it’s just a method inside the class.

So does this mean that class methods do not have access to class/member variables? So we use self.angle to give them access?

Consider,

>>> class Foo:
	faz = 'foo'
	def __init__(self):
		self.foo = self.faz

		
>>> Foo.faz    # the class variable
'foo'
>>> foo = Foo()
>>> foo.foo    # the instance variable
'foo'
>>> 
1 Like

Ahh ok I think I get it. Thanks for the example :slight_smile:

1 Like

You’re welcome. Something else to explore…

>>> class Foo:
	faz = 'foo'

	
>>> Foo.faz
'foo'
>>> foo = Foo()
>>> foo.faz
'foo'
>>> foo.faz = 'bar'
>>> foo.faz
'bar'
>>> Foo.faz
'foo'
>>> 

Note that by creating the assignment of the instance variable that it separates itself from the class to become a unique instance variable without affecting the class variable.

1 Like

Thanks, I tried messing with it. So to clarify, with the code below…

class Foo():
  faz = 'foo'

  def __init__(self):
    self.foo = self.faz

foo = Foo()

From this we then have the following variables…

Foo.faz #Class variable
foo.faz #Instance variable
foo.foo #Instance attribute?

Is this correct?

Hello mate, just to clarify your code a bit:

class Foo():
  faz = 'foo'

  def __init__(self):
    self.foo = 'faz'

foo = Foo()

From that code, you can call:
Foo.faz -> class variable or class attribute, whose value is 'foo'
foo.foo -> instance variable, instance attribute, object variable, object attribute. The value is 'faz'

'self.foo = self.faz' -> this is incorrect. There is no need to use self in the value, unless you are duplicating an attribute, e.g:

def __init__(self):
    self.foo = 'faz'
    self.faz = self.foo