Instances in python


#1

Hey guys,

Hope you guys are doing good and have enjoyed the weekend so far.
I had a doubt with classes, creating an instance of a class means to call the class and assign it to a variable?

for e.g.: Class abc(object):
def init(self, type):
self.letter = type

input_string = abc(). - So, this is where am creating the instance of the class or is it next line?
print input_string.letter

Could I have directly called:
abc.letter ?


#2

A direct call would not invoke the __init__ method, so letter would have to be a class variable, not an instance variable.

>>> class abc(object):
	letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
	def __init__(self, letter):
		self.letter = letter

		
>>> abc.letters
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
>>> abc.letter
Traceback (most recent call last):
  File "<pyshell#546>", line 1, in <module>
    abc.letter
AttributeError: type object 'abc' has no attribute 'letter'
>>> 

Aside

When you get to the Advanced Topics unit, this will make sense. It is how I generated the sequence above.

>>> ''.join([chr(x) for x in range(65, 91)] + [chr(x) for x in range(97, 123)])
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
>>> 

#3

Thank you so much for the explanation.
Also, I have noticed that some classes have init method in them and some do not.

Is it okay if I don’t initialize the class and directly create methods?

for example:
There is this piece of code which uses init

class Triangle(object):
  number_of_sides = 3 #member variable.
  def __init__(self, angle1, angle2, angle3):
    self.angle1 = angle1
    self.angle2 = angle2
    self.angle3 = angle3
  def check_angles(self):
    if self.angle1 + self.angle2 + self.angle3 == 180:
      return True
    else:
      return False
 
my_triangle =  Triangle(90,30,60)
print my_triangle.number_of_sides
print my_triangle.check_angles()

class Equilateral(Triangle):
  angle = 60 #member variable
  def __init__(self):
    self.angle1 = self.angle2 = self.angle3 = self.angle

here is another class example which does not use init. Here, the PartTimeEmployee class does not have init function in it

class Employee(object):
  """Models real-life employees!"""
  def __init__(self, employee_name):
    self.employee_name = employee_name

  def calculate_wage(self, hours):
    self.hours = hours
    return hours * 20.00

# Add your code below!
class PartTimeEmployee(Employee):
  def calculate_wage(self, hours):
    self.hours = hours
    return hours * 12.00
  def full_time_wage(self, hours):
    return super(Employee, self).calculate_wage(hours)

milton = PartTimeEmployee("Milton")
print milton.full_time_wage

#4

We are the designers, so it’s not about whether something should or shouldn’t be there, but whether we want it there, and for whatever reason. Classes that have no __init__ method will only give methods and class variables to their instances.

>>> class foo:
	bar = 'bar'
	def __repr__(self):
		return "Foo has no instance attributes."
	def set(self, foo):
		self['foo'] = foo
	def get(self):
		return self.bar

	
>>> bar = foo()
>>> bar.get()
'bar'
>>> bar
Foo has no instance attributes.
>>> bar.set('foo')
Traceback (most recent call last):
  File "<pyshell#582>", line 1, in <module>
    bar.set('foo')
  File "<pyshell#578>", line 6, in set
    self['foo'] = foo
TypeError: 'foo' object does not support item assignment
>>> 

Not to make any points with the above. Take the examples for what they are.

Classes without __init__ do not have to be instantiated. We can call the methods directly on the class, as we saw with variables, above.

Note that just because a class does not have an __init__ method doesn’t mean the instance doesn’t inherit one. Look to the super class to see if the method does in fact exist. It might be that instance parameters are still required by the class the instances inherit from.