Preview

04 - Methods and Attributes

 1. Have a look at the following example. Which of these statements is correct?
class Person:

    TITLES = ('Dr', 'Mr', 'Mrs', 'Ms')

    def __init__(self, title, name, surname):
        if title not in self.TITLES:
            raise ValueError("%s is not a valid title." % title)

        self.title = title
        self.name = name
        self.surname = surname

  The class attribute is TITLES

  The class attribute is 'Person'

  The class attributes are self.title and %title

  The class attributes are: Dr, Mr, Mrs, Ms as well as title, name, surname

 2. If we have a method which takes no arguments, then we still have to have one argument – the self. See fun() in the below example. Which statement is true.
# A simple example class
class Test:
     
    # A sample method 
    def fun(self):
        print("Hello")
 
# Driver code
obj = Test()
obj.fun()

  The example in the code does not use classes or objects

  The statement is correct

  The statement is incorrect as there is no need for the 'self'

  None of the above

 3. A function defined in a class is called a _______________

  attribute

  method

  object

  class definition

 4. Methods have access to all the data contained on the instance of the object; they can access and modify anything previously set on self

  TRUE

  FALSE

 5. Instance methods use self. They require an instance of the class in order to be used.

  TRUE

  FALSE

 6. Class attributes are attributes that are set at the class-level, as opposed to the instance-level. Normal attributes are introduced in the __init__ method, but some attributes of a class …………………

  None of the above

  hold for all instances in all cases

  hold for only one instance and this is why class attributes are needed

  do not exist

 7. There is a class of methods called static methods, that don't have access to self. Just like class attributes, they are methods that work without requiring an instance to be present.
class Car(object):
    ...
    def make_car_sound():
        print 'VRooooommmm!'

  FALSE

  TRUE

 8. In this example, we have defined the __init__ method to _________________________
# A Sample class with init method
class Person:
 
    # init method or constructor 
    def __init__(self, name):
        self.name = name
 
    # Sample Method 
    def say_hi(self):
        print('Hello, my name is', self.name)
 
p = Person('Mrs R Marvin')
p.say_hi()

  None of the above

  construct the object from the class itself

  delete the class and object on creation

  take the paraneter 'name' along with the usual 'self' parameter

 9. A ___________________is an action that an object can perform. For example, in VB.Net "Add" is a___________ of the ComboBox object that adds a new entry to a combo box.

  method

  variable

  function

  attribute

 10. A method created in a Class is nothing more that a Function or a Sub

  TRUE

  FALSE

 11. In Python, instance variables are variables whose value is assigned inside a constructor or method with self. Class variables are variables whose ___________________

  value is assigned in the object itself

  method is assigned in the class

  method is created in the object

  value is assigned in the class

 12. In the following code, which line is referring to the instance variable?
# Class for Computer Science Student
class CSStudent:
 
    
    stream = 'cse'            
 
    # The init method or constructor
    def __init__(self, roll):
   
        
        self.roll = roll       
  
# Objects of CSStudent class
a = CSStudent(101)
b = CSStudent(102)
  
print(a.stream)  # prints "cse"
print(b.stream)  # prints "cse"
print(a.roll)    # prints 101
  
# Class variables can be accessed using class
# name also
print(CSStudent.stream) # prints "cse" 

  None of the above

  stream = 'cse'

  b = CSStudent(102)

  self.roll = roll

 13. In the following code, which line is referring to to the class variable?
# Class for Computer Science Student
class CSStudent:
 
    
    stream = 'cse'            
 
    # The init method or constructor
    def __init__(self, roll):
   
        
        self.roll = roll       
  
# Objects of CSStudent class
a = CSStudent(101)
b = CSStudent(102)
  
print(a.stream)  # prints "cse"
print(b.stream)  # prints "cse"
print(a.roll)    # prints 101
  
# Class variables can be accessed using class
# name also
print(CSStudent.stream) # prints "cse" 

  self.roll = roll

  None of the above

  b = CSStudent(102)

  stream = 'cse'

 14. What is the output from the following code?
class Robot:
    pass

if __name__ == "__main__":
    x = Robot()
    y = Robot()
    y2 = y
    print(y == y2)
    print(y == x)

  False,False

  False,True

  True, False

  True,True

 15. What is the following code doing?
x = MyClass()

  x is calling the class MyClass()

  It doesn't do anything -you cannot assign a class to a variable

  it creates a new instance of the class and assigns this object to the local variable x.

  x calls the class and returns an Error

 16. x = MyClass() << In this case, the instantiation operation (“calling” a class object) creates an empty object.

  True, False

  FALSE

 17. The method in the following code is ______________________ and the output (by adding to the list defined in the class) is:
class Dog:

    def __init__(self, name):
        self.name = name
        self.tricks = []    # creates a new empty list for each dog

    def add_trick(self, trick):
        self.tricks.append(trick)


d=Dog("Fido")
d.add_trick("roll over")
d.add_trick("beg for food")
print(d.name,"can",d.tricks)

  add_trick / Fido can ['roll over', 'beg for food']

  self.tricks / Fido can ['roll over', 'beg for food']

  None of the above

  self.tricks=[] / Error (as nothing was added to the list)

 18. Can you predict the output of the following code?
class Robot:
 
    def __init__(self, name=None):
        self.name = name   
        
    def say_hi(self):
        if self.name:
            print("Hi, I am " + self.name)
        else:
            print("Hi, I am a robot without a name")
    

x = Robot()
x.say_hi()
y = Robot("Mrs Marvin")
y.say_hi()

  Hi, I am a robot without a name, Hi, I am Mrs Marvin

  Error - it is not possible to create a class using x and y

  Hi, I am Mrs Marvin

  x,y,x,y

 19. In the following code, the methods are x and y, and the object is say_hi
class Robot:
 
    def __init__(self, name=None):
        self.name = name   
        
    def say_hi(self):
        if self.name:
            print("Hi, I am " + self.name)
        else:
            print("Hi, I am a robot without a name")

  FALSE

  TRUE

 20. Which of the following are methods?
class Robot:
 
    def __init__(self, name=None):
        self.name = name   
        
    def say_hi(self):
        if self.name:
            print("Hi, I am " + self.name)
        else:
            print("Hi, I am a robot without a name")
            
    def set_name(self, name):
        self.name = name
        
    def get_name(self):
        return self.name
    

x = Robot()
x.set_name("Henry")
x.say_hi()
y = Robot()
y.set_name(x.get_name())
print(y.get_name())

  All of the above are valid methods in this program

  set_name

  say_hi

  get_name

 21. Every object in Python has attributes. You can get a list of those attributes using the built-in “dir” function. For example:
>>> s = 'abc'
>>> len(dir(s))
71
>>> dir(s)[:5]
['__add__', '__class__', '__contains__', '__delattr__', '__doc__']

>>> i = 123
>>> len(dir(i))
64
>>> dir(i)[:5]
['__abs__', '__add__', '__and__', '__class__', '__cmp__']

  FALSE

  TRUE

 22. In this example, 'name' is an attribute.
class Robot:
 
    def __init__(self, name=None):
        self.name = name   
        
    def say_hi(self):
        if self.name:
            print("Hi, I am " + self.name)
        else:
            print("Hi, I am a robot without a name")
            
    def set_name(self, name):
        self.name = name
        
    def get_name(self):
        return self.name

  FALSE

  TRUE

 23. In this example,we have used an attribute to store a Class-wide, Class-specific constant which is….
class Circle(object):
    pi = 3.14159

    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return Circle.pi * self.radius * self.radius

Circle.pi
## 3.14159

c = Circle(10)
c.pi
## 3.14159
c.area()
## 314.159

  pi

  area

  radius

  Circle

 24. No attributes have been defined in the following program.
class CoffeeMachine:
    name = ""
    beans = 0
    water = 0
 
    def __init__(self, name, beans, water):
        self.name = name
        self.beans = beans
        self.water = water

  TRUE

  FALSE

 25. What happens if both instance attribute and class attribute is defined?

  the class namespace always comes first

  Both are printed or used

  In that case, the instance namespace takes supremacy over the class namespace.

  None of the above