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: Dr, Mr, Mrs, Ms as well as title, name, surname

  The class attributes are self.title and %title

 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 statement is correct

  The example in the code does not use classes or objects

  None of the above

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

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

  method

  object

  class definition

  attribute

 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

  FALSE

  TRUE

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

  hold for all instances in all cases

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

  None of the above

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

  delete the class and object on creation

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

  None of the above

  construct the object from the class itself

 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

  attribute

  function

  variable

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

  FALSE

  TRUE

 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 class

  method is assigned in the class

  method is created in the object

  value is assigned in the object itself

 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

  self.roll = roll

  stream = 'cse'

  b = CSStudent(102)

 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" 

  None of the above

  self.roll = roll

  stream = 'cse'

  b = CSStudent(102)

 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

  True,True

  False,False

  False,True

 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.

  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)

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

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

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

  None of the above

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

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

  x,y,x,y

  Hi, I am Mrs Marvin

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

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

  set_name

  All of the above are valid methods in this program

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

  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

  area

  pi

  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

  FALSE

  TRUE

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

  the class namespace always comes first

  None of the above

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

  Both are printed or used