Python classes and objects

This study set covers the fundamental concepts of Python classes and objects, including definitions, principles, and practical applications. It serves as a comprehensive guide for college students seeking to understand object-oriented programming in Python.

Harper2006·72 flashcards·72 questions
collegecomputer_scienceprogramming
0
Known
1 / 72
0
Learning
Front

Class → Definition

Tap to flip
Back

A class is a blueprint for creating objects that define a set of attributes and methods.

Tap to flip
Got it
Still learning

Quiz(72 questions)

Question 1 of 72

1. What is an attribute in a class?

Terms in this Study Set(72)

Basics of Classes and Objects(16)

Class → Definition

A class is a blueprint for creating objects that define a set of attributes and methods.

Object → Definition

An object is an instance of a class, containing data and behavior defined by the class.

True or False: Classes can contain variables.

True - Classes can have attributes (variables) that store data relevant to the object.

Constructor → Purpose

A constructor initializes an object's attributes when it is created, typically using the __init__ method.

Fill in the blank: An object is created using the ______ operator.

An object is created using the instantiation operator.

Instance vs Class Variable

Instance variables are unique to each object, while class variables are shared among all instances.

Define encapsulation.

Encapsulation is a principle of bundling data and methods that operate on that data within one unit, restricting access to some components.

Method → Definition

A method is a function defined within a class that operates on instances of that class.

Example of a simple class.

class Car: def __init__(self, make, model): self.make = make self.model = model

True or False: You can create multiple objects from one class.

True - Multiple objects can be instantiated from the same class, each with unique attributes.

Attribute → Definition

An attribute is a variable that belongs to a class or an object, holding data related to that class.

Question: Why use classes?

Classes promote organization, code reuse, and encapsulation of data and behavior.

Class vs Object

A class is a blueprint, while an object is a specific instance of that blueprint.

Constructor Example.

class Person: def __init__(self, name): self.name = name

Inheritance → Definition

Inheritance allows a class to inherit attributes and methods from another class, promoting code reuse.

Usage of 'self' in methods.

'self' refers to the instance of the class, allowing access to its attributes and methods.

Attributes and Methods(20)

Attribute → Definition

An attribute is a variable that belongs to a class. It holds the state or data of an object created from the class.

What is a method?

A method is a function defined within a class that describes the behaviors of the objects created from that class.

True or False: Methods can access class attributes.

True. Methods can access and modify attributes using the 'self' keyword to refer to the instance.

Fill in the blank: An instance variable is defined with the prefix ___

'self.' indicating that it belongs to an instance of the class.

How to define a class attribute?

Class attributes are defined directly within the class body, outside of any methods: class MyClass: class_attribute = 'value'

What does 'self' refer to?

'self' refers to the instance of the class itself within instance methods, allowing access to its attributes and methods.

Method vs. Function

A method is a function that is associated with an object. Functions can exist independently, while methods are bound to class instances.

Constructor → Purpose

The constructor method __init__ initializes new objects, setting the initial state using passed arguments.

Example of a simple method.

class Dog: def bark(self): return 'Woof!' Here, 'bark' is a method of the Dog class.

How to call a method?

To call a method, use the syntax: instance_name.method_name(). For example, dog_instance.bark().

Difference between instance and class attributes.

- Instance attributes are unique to each instance. - Class attributes are shared among all instances.

What is a property?

A property is a special type of attribute that uses getter/setter methods for controlled access and modification.

How to access an attribute?

Attributes can be accessed using dot notation: instance_name.attribute_name.

True or False: Attributes can only be strings.

False. Attributes can be of any data type including integers, lists, and even other objects.

Define a private attribute.

Private attributes are prefixed with '__', making them inaccessible from outside the class. Example: __private_attr.

What is a static method?

A static method does not modify or access instance data. It is defined with @staticmethod decorator.

Example of using 'self' in a method.

class Car: def __init__(self, make): self.make = make In this example, 'self.make' refers to the instance variable.

How to define an instance method?

An instance method is defined with at least one parameter: 'self'. For example: def instance_method(self):.

What happens if an attribute is not defined?

Accessing an undefined attribute results in an AttributeError. Always ensure attributes are initialized.

What is an attribute in a class?

An attribute is a variable that belongs to a class. - Stores data related to an object. - Can be instance or class attributes. - Example: `self.balance` in a `BankAccount` class.

Inheritance and Polymorphism(20)

Inheritance in Python

Inheritance allows one class to inherit attributes and methods from another class, promoting code reuse.

What is a base class?

A base class is the class from which other classes inherit properties and methods.

True or False: Subclasses can override base class methods.

True. Subclasses can provide a new implementation of a method defined in the base class.

What is a subclass?

A subclass is a class that derives from a base class, inheriting its features.

Fill in the blank: A subclass is also known as a ___ class.

Derived.

Multi-level inheritance

Multi-level inheritance occurs when a class inherits from another subclass, forming a hierarchy.

Polymorphism definition

Polymorphism allows methods to do different things based on the object calling them.

Example of polymorphism

Consider the method `speak()` in classes `Dog` and `Cat`. Each class implements `speak()` differently.

What is method overriding?

Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its base class.

True or False: Polymorphism only applies to classes.

False. Polymorphism can also apply to functions and data types.

Comparison: Inheritance vs Composition

- Inheritance: 'is-a' relationship. - Composition: 'has-a' relationship.

What is the `super()` function?

`super()` is used to call a method from the base class in a subclass.

Cause → Effect: Use of inheritance

Cause: Code reuse through inheritance. Effect: More maintainable and organized code.

Abstract classes

An abstract class cannot be instantiated and may contain abstract methods that must be implemented by subclasses.

Example of an abstract method

In an abstract class `Shape`, the method `area()` is an abstract method that must be defined in derived classes.

What is duck typing?

Duck typing allows an object to be used based on its methods and properties rather than its actual type.

Encapsulation in inheritance

Encapsulation restricts access to certain attributes and methods, even when inherited.

True or False: Python supports multiple inheritance.

True. Python allows a class to inherit from multiple classes.

Dynamic dispatch

Dynamic dispatch refers to the method resolution that occurs at runtime based on the object type.

What is overriding?

Overriding allows a subclass to provide a specific implementation of a method already defined in its superclass.

Advanced Class Features(16)

What is a class method?

A class method is a method that is bound to the class rather than its instance. It uses the @classmethod decorator. It receives the class as its first argument, typically named 'cls'.

True or False: Class methods can modify class state.

True. Class methods can access and modify class state that applies across all instances.

What is a static method?

A static method does not receive an implicit first argument (neither self nor cls). It is defined using the @staticmethod decorator and behaves like a regular function.

Compare class methods and static methods.

Class methods: operate on class level, receive 'cls'. Static methods: operate independently, no 'self' or 'cls'.

Fill in the blank: The ______ method is used to access an object's attributes directly.

The property method is used to access an object's attributes directly.

How to define a property?

Use the @property decorator to define a method as a property. This allows controlled access to an attribute.

What is the purpose of the @property decorator?

The @property decorator is used to define a method that can be accessed like an attribute, enabling encapsulation.

True or False: Properties can have setters and getters.

True. Properties can have both getters and setters defined using @property and @attribute_name.setter.

Cause → Effect: Using properties in a class.

Using properties increases data encapsulation and allows validation without changing the interface.

Show an example of a class method.

Example: ```python class MyClass: count = 0 @classmethod def increment_count(cls): cls.count += 1 ```

What is the significance of the @staticmethod decorator?

Static methods do not access or modify class or instance state. They are utility functions related to the class.

Fill in the blank: The ______ method allows us to define behavior for when an attribute is set.

The setter method allows us to define behavior for when an attribute is set.

How does a getter work?

A getter retrieves the value of a private attribute. It's defined using the @property decorator.

True or False: You can override properties in subclasses.

True. Properties can be overridden in subclasses, allowing for specialized behavior.

What is the purpose of static methods in a class?

Static methods provide a way to group related functions to the class, without needing an instance.

List two benefits of using class methods.

- Access to class state. - Factory methods for instance creation.

Questions in this Study Set(72)

1. What is an attribute in a class?

A.A variable that holds the state of an object
B.A function that performs a task
C.A special type of method
D.A reserved keyword in Python

2. What does inheritance allow in Python?

A.Code reuse between classes
B.Creating standalone functions
C.Data encapsulation in modules
D.Type checking for variables

3. What is a class in object-oriented programming?

A.A blueprint for creating objects
B.An instance of an object
C.A type of variable
D.A method for data processing

4. What does the @classmethod decorator indicate?

A.It defines a method that belongs to the class instead of an instance.
B.It defines a method that cannot be overridden in subclasses.
C.It creates a method that only modifies instance variables.
D.It allows a method to inherit from another class.

5. What is the purpose of a method in a class?

A.To define the attributes of a class
B.To modify class attributes directly
C.To perform actions related to an object
D.To create a new instance of a class

6. Which of the following best describes a base class?

A.A class that inherits properties from another
B.The class that defines base functionalities
C.A class that has no derived classes
D.A class that uses multiple inheritance

7. Which of the following best describes an object?

A.A specific instance of a class
B.A method that belongs to a class
C.A public variable in a class
D.A type of class

8. True or False: Static methods can modify instance state.

A.True
B.False
C.Only in certain cases
D.Depends on the decorator

9. Which keyword is used to refer to the instance of a class in its methods?

A.self
B.instance
C.class
D.this

10. True or False: Subclasses can implement new behaviors for inherited methods.

A.True
B.False
C.Only in multiple inheritance
D.Only in abstract classes

11. True or False: A class can be considered a function.

A.True
B.False
C.Only in certain languages
D.Only if it has methods

12. Which of the following methods does not take 'self' or 'cls' as an argument?

A.Static method
B.Class method
C.Instance method
D.Getter method

13. True or False: Instance attributes are shared among all instances of a class.

A.True
B.False
C.Only if declared as public
D.Depends on the method

14. What defines a subclass?

A.A standalone class that does not inherit
B.A class that inherits features from a base class
C.A class that cannot have methods
D.A class that can only be abstract

15. What is the purpose of a constructor in a class?

A.To initialize an object's attributes
B.To define a method
C.To create a class
D.To destruct an object

16. Fill in the blank: The ______ decorator allows you to define a method that is treated like an attribute.

A.staticmethod
B.property
C.classmethod
D.setter

17. What does the __init__ method do in a class?

A.Defines class methods
B.Initializes new objects
C.Modifies existing objects
D.Deletes class attributes

18. Fill in the blank: A subclass can also be referred to as a ___ class.

A.Abstract
B.Base
C.Derived
D.Peer

19. Fill in the blank: An object is created using the ______ operator.

A.declaration
B.instantiation
C.definition
D.creation

20. What is a potential benefit of using class methods?

A.They can access instance variables directly.
B.They can serve as factory methods for creating instances.
C.They are automatically invoked when an instance is created.
D.They can only modify private attributes.

21. What is the correct syntax to define a class attribute?

A.class MyClass: class_attribute = 'value'
B.def MyClass.class_attribute():
C.MyClass.class_attribute = 'value'
D.attribute MyClass.class_attribute = 'value'

22. What is an example of multi-level inheritance?

A.Class A inherits from Class B, which inherits from Class C
B.Class A inherits from Class B and Class C
C.Class A and B are independent classes
D.Class A is a subclass of Class A

23. What is the difference between instance and class variables?

A.Instance variables are shared, class variables are unique
B.Class variables are shared, instance variables are unique
C.Both are shared
D.Both are unique

24. Which statement correctly compares class methods and instance methods?

A.Class methods are called on instances, while instance methods are called on classes.
B.Class methods cannot access instance variables; instance methods can.
C.Both can modify the class state.
D.Instance methods do not have access to parameters.

25. How do you access an attribute of an object?

A.instance_name:attribute_name
B.instance_name.attribute_name()
C.instance_name.attribute_name
D.get(instance_name, attribute_name)

26. What does polymorphism in Python allow?

A.Methods to be defined multiple times
B.Different classes to define the same method
C.Classes to create unique attributes
D.Static type checking

27. Define encapsulation in the context of classes.

A.Bundling data and methods within one unit
B.Separating data from methods
C.Creating multiple instances of a class
D.Inheriting attributes from other classes

28. What does the @property decorator allow you to do?

A.Create static methods.
B.Define attributes that can incorporate logic.
C.Hide all methods from subclasses.
D.Override class methods.

29. What is a private attribute?

A.An attribute accessible from any class
B.An attribute only accessible within its class
C.An attribute shared among all instances
D.An attribute that must be public

30. Consider a class `Bird` and class `Fish`. If both have a method `move()`, what is this an example of?

A.Overriding
B.Encapsulation
C.Polymorphism
D.Inheritance

31. What is a method in a class?

A.A function defined within a class
B.A variable associated with a class
C.An object created from a class
D.A type of class

32. True or False: You can have multiple properties with the same name in a class.

A.True
B.False
C.Only if they are static
D.Depends on the class structure

33. Which of the following best describes a static method?

A.A method that can access instance data
B.A method that cannot modify class or instance data
C.A method that is always public
D.A method that must return a value

34. What is method overriding?

A.Creating a new method in the base class
B.Providing a new implementation of an inherited method
C.Defining a method without a return type
D.Using a method with the same name in different modules

35. Which of the following is an example of a simple class definition?

A.class Vehicle: def __init__(self, type): self.type = type
B.class Vehicle: def Vehicle(self, type): self.type = type
C.Vehicle: class __init__(self, type): self.type = type
D.class Vehicle: self.type = type

36. In which scenario would you prefer using a static method over a class method?

A.When the method needs to modify class variables.
B.When the method does not need to access instance or class state.
C.When you need to initialize instances.
D.When you want to enforce access to instance variables.

37. How is an instance method defined?

A.def method_name(self):
B.def method_name():
C.method_name(def self):
D.def self.method_name():

38. True or False: Polymorphism is limited to class methods only.

A.True
B.False
C.Only in abstract classes
D.Only for functions

39. True or False: A single class can create multiple objects.

A.True
B.False
C.Only if they have the same attributes
D.Only if they share methods

40. What is a setter method in the context of properties?

A.A method that retrieves the value of an attribute.
B.A method that defines behavior when an attribute is set.
C.A method that prevents access to the attribute.
D.A method that creates new instances.

41. What happens if you try to access an undefined attribute?

A.It returns None
B.It creates a new attribute
C.It raises an AttributeError
D.It defaults to zero

42. How does inheritance differ from composition?

A.Inheritance represents 'has-a' relationships
B.Composition is used for code reuse
C.Inheritance represents 'is-a' relationships
D.Composition cannot use methods

43. What is an attribute in the context of a class?

A.A method associated with a class
B.A variable that holds data related to a class or object
C.The name of the class
D.The constructor of the class

44. What happens if you try to access a non-existent property in a class?

A.It raises an AttributeError.
B.It returns None.
C.It creates the property dynamically.
D.It defaults to a class-level value.

45. Which of the following is NOT a characteristic of a method?

A.It is defined within a class
B.It can access instance attributes
C.It does not require parameters
D.It describes behaviors of objects

46. What does the `super()` function do?

A.Creates a new instance of the base class
B.Calls a method from the base class in a subclass
C.Overwrites a subclass method
D.Provides static typing

47. Why are classes used in programming?

A.To improve organization and code reuse
B.To make programming more complex
C.To reduce the number of functions
D.To limit the use of variables

48. How can class methods contribute to a more organized code structure?

A.By allowing direct access to instance variables.
B.By grouping related functionality within the class.
C.By enabling global variable access.
D.By making all methods static.

49. What distinguishes instance attributes from class attributes?

A.Instance attributes are shared; class attributes are unique
B.Class attributes can only be modified by methods
C.Instance attributes are unique to each instance; class attributes are shared
D.Class attributes cannot be accessed directly

50. What is the effect of using inheritance in code design?

A.Reduces code redundancy
B.Increases complexity
C.Requires more memory
D.Slows down execution

51. What is the relationship between a class and an object?

A.A class is an instance of an object
B.An object is a blueprint for a class
C.A class is a blueprint, while an object is an instance of that blueprint
D.Classes and objects are the same

52. Which term describes the practice of using properties in a class?

A.Encapsulation
B.Inheritance
C.Polymorphism
D.Abstraction

53. In the statement 'self.balance = 0', what is 'balance'?

A.A class attribute
B.A method
C.An instance variable
D.A private attribute

54. Which of the following describes an abstract class?

A.Can be instantiated freely
B.Cannot contain methods
C.Serves as a template for subclasses
D.Can only contain concrete methods

55. What does the 'self' parameter refer to in class methods?

A.The class itself
B.The instance of the class
C.The parent class
D.The method name

56. Fill in the blank: A class method receives ______ as its first parameter.

A.self
B.cls
C.attr
D.instance

57. What is the purpose of a property in a class?

A.To store metadata
B.To enforce controlled access to attributes
C.To define class-level constants
D.To represent methods

58. What is an example of an abstract method?

A.A method that has no return value
B.A method that must be defined in derived classes
C.A method that is private
D.A method that uses static typing

59. Inheritance allows a class to:

A.Create multiple instances from one class
B.Inherit attributes and methods from another class
C.Combine multiple classes into one
D.Avoid using classes

60. True or False: Properties can be overridden in subclasses.

A.True
B.False
C.Only if they are static properties
D.Depends on access modifiers

61. How do you call a method on an object?

A.object.method_name
B.method_name(object)
C.object.method_name()
D.call object.method_name()

62. What does duck typing in Python signify?

A.Type checking at compile-time
B.Using an object's methods and properties for behavior
C.Creating subclasses for every type
D.Enforcing strict typing for functions

63. Which of the following statements best describes instance variables?

A.They are unique to each object created from a class.
B.They are shared among all objects of a class.
C.They can only be defined outside of a class.
D.They are only used to store class methods.

64. Which of the following statements is true about static methods in a class?

A.Static methods do not access class or instance attributes.
B.Static methods can modify instance attributes.
C.Static methods require access to the class state.
D.Static methods are called using an instance of the class.

65. What is the main difference between a method and a function?

A.Methods can exist independently; functions cannot
B.Functions can access class attributes; methods cannot
C.Methods are associated with objects; functions are not
D.There is no difference

66. How does encapsulation relate to inheritance?

A.It allows all attributes to be public
B.It restricts access to certain attributes and methods
C.It removes the need for base classes
D.It enforces single inheritance

67. Which of the following is a valid way to define a class in Python?

A.class MyClass:
B.MyClass class:
C.define MyClass:
D.class: MyClass

68. True or False: Python supports multiple inheritance.

A.True
B.False
C.Only in classes with no methods
D.Only with explicitly defined interfaces

69. Which of the following statements about attributes in a class is true?

A.Attributes can be either instance or class attributes.
B.Attributes are only accessible within the constructor.
C.Attributes must always be initialized with a value.
D.Attributes can only hold strings.

70. What is dynamic dispatch?

A.Resolving method calls at compile time
B.Choosing which method to execute based on the object type at runtime
C.Storing method references in variables
D.Creating dynamic variables

71. In the context of a class, which of the following best describes an instance method?

A.An instance method is a function that works with instance data and requires 'self' as its first parameter.
B.An instance method cannot access instance attributes.
C.An instance method must always return a value.
D.An instance method is the same as a class method.

72. What is meant by overriding in the context of inheritance?

A.Creating a new base class
B.Providing a specific implementation of an inherited method
C.Requiring a method to not have a return type
D.Using the same method name across all classes

Related Study Sets

Create Your Own Study Set

Upload a PDF, paste your notes, or describe a topic – AI generates flashcards, quizzes and more in seconds.