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 attributes are self.title and %title

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

  The class attribute is 'Person'

 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 incorrect as there is no need for the 'self'

  None of the above

  The statement is correct

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

  class definition

  attribute

  object

  method

 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.

  FALSE

  TRUE

 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 …………………

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

  do not exist

  None of the above

  hold for all instances in all cases

 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()

  delete the class and object on creation

  construct the object from the class itself

  None of the above

  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.

  attribute

  method

  variable

  function

 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 ___________________

  method is assigned in the class

  value is assigned in the class

  value is assigned in the object itself

  method is created in the object

 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" 

  b = CSStudent(102)

  self.roll = roll

  stream = 'cse'

  None of the above

 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" 

  b = CSStudent(102)

  None of the above

  stream = 'cse'

  self.roll = roll

 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)

  True, False

  False,True

  True,True

  False,False

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

  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

  x is calling the class MyClass()

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

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

  FALSE

  True, 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)

  None of the above

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

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

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

 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

  Hi, I am Mrs Marvin

  x,y,x,y

  Error - it is not possible to create a class using x and 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")

  TRUE

  FALSE

 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())

  get_name

  All of the above are valid methods in this program

  say_hi

  set_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__']

  TRUE

  FALSE

 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

  TRUE

  FALSE

 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

  radius

  pi

  Circle

  area

 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

  FALSE

  TRUE

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

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

  Both are printed or used

  None of the above

  the class namespace always comes first