I don't quite understand a few concepts


#1

Hello,
I am slightly confused about classes and the dot notation.

Here:

class Animal(object):
  """Makes cute animals."""
  is_alive = True
  def __init__(self, name, age):
    self.name = name
    self.age = age

zebra = Animal("Jeffrey", 2)
giraffe = Animal("Bruce", 1)
panda = Animal("Chad", 7)

print zebra.name, zebra.age, zebra.is_alive
print giraffe.name, giraffe.age, giraffe.is_alive
print panda.name, panda.age, panda.is_alive

In the init(), the values for the attributes ‘age’ and ‘name’ are assigned to self.age and self.name to be later used.
However, for the variable ‘is_alive’, it is used directly in the last three lines without it being defined.

Why is that so? I am confused as to why it wouldn’t do something like:

self.is_alive = is_alive

Just as we did for ‘age’ and ‘name’.

Also, does the name of the attribute and the word that comes after the word have to be the same? For example, will it still work if I did:

def __init__(self, name, age):
  self.nam = name
  self.ag = age

I feel like it should, but I’m not too sure.

Sorry if this is poorly asked, I’m not sure how to explain it concisely.


#2

because is_alive is a class variable, class variables are automatically added to self

that would work, but its quite uncommon to do so.

= means assign, so then you assign the parameters (name and age) to differently named instance variables (self.nam and self.ag).


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.