Codecademy Forums

FAQ: Learn Python: Classes - Self

Two questions if I may:

  1. Why do we write self.radius and self.pi the same when we are creating the circumference method? pi is a class parameter and self.radius is an instance variable, no?

  2. Why can’t def circumference(self): be at the same indentation as the self.radius code?


to access class variables, instance variables and methods within a method you need self.

class variable and methods are automatically added to self

Why would you want to do that? You want to add the method to the class, not the constructor

1 Like

It simply depends upon how you want to construct the class, and what you want each object to do. In real life, i.e., when not following a lesson plan, you can do it almost any way that you want.

In this particular design,
self.radius sets an attribute of the particular Circle object.
circumference() is a method of the Circle object.

Since the circumference (and area) of a given circle are fixed, self.circumference and self.area could indeed be included in the constructor to establish those values as object attributes. However, presumably in order to easily illustrate attributes and methods, the course author chose not to do it that way.


how can i access the argument passesd at the time of instance in another method?

here what i want to say:
class test:
def init(self,name):
self.shame = name
def func(self):
return name

if i run
foo = test(“trial_name”)

i should get “trial_name” printed

class test:
  def init(self,name): = name
  def func(self):

foo = test('trial_name')
print (foo.func())    # trial_name

Can you explain this again?
How are we able to get self.radius?
It is because we have diameter as an argument in method?
Or we just can create any instance variable with the value we define.

radius would be a computed value if the parameter is diameter. I would write a separate method since we want the radius to reflect the currrent diameter, and we may want our class to allow that to be changeable.

def  get_radius(self):
    return self.diameter / 2

I’ll need to be apprised of the exercise, so please post a link and we can look at this a little further.

class Circle:
pi = 3.14
def init(self, diameter):
print(“Creating circle with diameter {d}”.format(d=diameter))
# Add assignment for self.radius here:
self.radius = diameter / 2

Ah, so the instructions stipulate writing the radius as a part of the initialization. This will be okay if the circle instance is to be static, and unchangeable.

Note that the instance has no diameter attribute, only a radius computed from the parameter.

1 Like