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

  The class attribute is TITLES

  The class attribute is 'Person'

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

  The statement is correct

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

  object

  class definition

  method

  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

  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 all instances in all cases

  do not exist

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

  None of the above

 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!'

  TRUE

  FALSE

 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

  None of the above

  construct the object from the class itself

  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.

  variable

  function

  attribute

  method

 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 class

  method is created in the object

  method is assigned in the class

  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" 

  stream = 'cse'

  b = CSStudent(102)

  None of the above

  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" 

  b = CSStudent(102)

  stream = 'cse'

  self.roll = roll

  None of the above

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

  True, False

  False,False

  True,True

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

  x calls the class and returns an Error

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

  x is calling the class MyClass()

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

 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)

  None of the above

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

  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 Mrs Marvin

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

  x,y,x,y

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

  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

  get_name

  say_hi

 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

  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

  Circle

  pi

  radius

  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.

  the class namespace always comes first

  None of the above

  Both are printed or used