Write OOP classes to handle the following scenarios:
- A user can create and view 2D coordinates
- A user can find out the distance between 2 coordinates
- A user can find find the distance of a coordinate from origin
- A user can check if a point lies on a given line
- A user can find the distance between a given 2D point and a given line
Example 1
Explanation
- Defines a Point class with x and y coordinates, including methods to display the point, calculate Euclidean distance between two points, and distance from origin
- Implements a Line class representing linear equations in form Ax + By + C = 0 with methods to check if a point lies on the line and calculate shortest distance from a point to the line
- Uses special methods like init and str for object initialization and string representation
- The euclidean_distance method calculates straight-line distance using the Pythagorean theorem
- Both classes store coordinate data and provide geometric calculations for points and lines in 2D space
Example 2
Explanation
- Creates two Point objects with coordinates (1,2) and (3,4) respectively
- Creates a Line object with parameters (3,4,5) - likely slope, y-intercept, and possibly x-coordinate
- Calls print() function on each object which will display their string representations
- Uses Point and Line classes from an imported graphics or geometry module
- Output shows the textual representation of each geometric object's properties
Output
Example 3
Explanation
- Calls the euclidean_distance method on object p1 to calculate the straight-line distance to point p2
- Uses the mathematical formula √[(x₂-x₁)² + (y₂-y₁)² + (z₂-z₁)²] for 3D space or similar for lower dimensions
- Returns a single floating-point number representing the distance between the two points
- Both p1 and p2 must be point objects with coordinate attributes (x, y, z)
- No side effects occur; this is a read-only calculation that doesn't modify either point object
Output
Example 4
Explanation
- Calls the distance_from_origin method on object p1 to calculate its distance from the coordinate origin (0,0)
- Uses the Euclidean distance formula to compute the straight-line distance between p1's coordinates and the origin
- Returns a numerical value representing the calculated distance as a float or integer
- Method likely uses attributes like p1.x and p1.y internally to perform the calculation
- Side effect is returning the computed distance value without modifying the original p1 object
Output
Example 5
Explanation
- Creates a Line object with coefficients (1,1,-2) representing equation x+y-2=0 and a Point object at coordinates (1,1)
- Prints string representations of both the line and point objects
- Checks if the first point lies on the line and calculates the shortest distance from the point to the line
- Tests the same operations with a second point at (1,5) that doesn't lie on the line
- Outputs boolean values for point-on-line tests and numerical distances for shortest distances
Output
How objects access attributes
Example 6
Explanation
- Defines a Person class with constructor that stores name and country attributes
- Includes a greet method that prints different greetings based on the person's country
- Uses conditional logic to check if country equals 'india' and prints 'Namaste' or 'Hello' accordingly
- Creates object instances that can call the greet method to display personalized messages
- Has no direct output when defined, but will print greetings when greet() is called on instances
Example 7
Explanation
- Creates a Person object instance with name 'Madhu' and country 'India' using the Person constructor/class
- The Person class is likely defined elsewhere with attributes for storing personal information like name and location
- This line initializes an object that can later have its attributes accessed through dot notation like p.name or p.country
- No immediate output or side effects occur - just object creation
- The variable p now holds a reference to this Person object for future attribute access or method calls
Example 8
Explanation
- Accesses the
nameattribute of the objectp - Likely retrieves a string value representing the name of whatever object
prefers to - Commonly used with objects like files, processes, or custom classes that have a name property
- Returns the name value directly without modifying anything else
- If
pdoesn't have anameattribute, this would raise an AttributeError
Output
Example 9
Explanation
- Calls the greet() method on the object p, which is likely an instance of a class
- This method probably prints a greeting message or returns a welcome string
- The dot notation (p.greet()) is Python's syntax for accessing object methods
- Expected output would be whatever the greet() method is programmed to display
- Side effect depends on the implementation but typically involves printing text or returning a string
Output
Example 10
Explanation
- Attempts to access a
genderattribute on an objectpthat doesn't have this attribute defined - Will raise an
AttributeErrorexception since the attribute doesn't exist on the object - Common Python error when trying to access properties that weren't initialized or defined
- Demonstrates Python's strict attribute access behavior - no graceful fallback like some other languages
- Typical debugging scenario when working with object-oriented code and attribute names
Output
Attribute creation from outside of the class
Example 11
Explanation
- Sets the gender attribute of the object
pto the string value 'Male' - This is a simple attribute assignment operation that modifies the object's state
- No functions or APIs are called, just direct attribute setting
- The object
pnow has its gender property updated to 'Male' - This change persists in the object until modified again
Example 12
Explanation
- Accesses the gender attribute of the object
p - Likely retrieves a gender value stored in the object's properties
- Commonly used with objects that represent people or entities with demographic attributes
- Returns the gender information as a string or similar data type
- May raise an AttributeError if the
genderattribute doesn't exist on objectp
Output
Reference Variables
- Reference variables hold the objects
- We can create objects without reference variable as well
- An object can have multiple reference variables
- Assigning a new reference variable to an existing object does not create a new object
Example 13
Explanation
- Creates a Person class with name and gender attributes, then makes two references (p and q) pointing to the same object instance
- The variable p doesn't contain the actual object, but holds a reference/address to where the object exists in memory
- Both p and q point to the exact same object in memory, so they're aliases for the same instance
- No new object is created - both variables reference the identical object created by Person()
- This demonstrates Python's object model where variables are references to objects rather than containers for objects
Example 14
Explanation
- This code prints the memory addresses (identity) of two variables
pandqusing theid()function - The
id()function returns a unique integer representing the object's location in memory - It's commonly used to check if two variables reference the same object or different objects
- If both variables have the same
id()value, they point to the exact same object in memory - The output shows two integer values representing where
pandqare stored in memory
Output
Example 15
Explanation
- The code prints the
nameattribute of two objects,pandq, to the console. - It then changes the
nameattribute of the objectqto "Dadi". - After the change, it prints the
nameattribute ofqagain, showing the updated value. - The
nameattribute ofpremains unchanged and is printed after the modification ofq.
Output
Pass by reference
Example 16
Explanation
- Defines a
Personclass with an__init__method to initializenameandgenderattributes. - Implements a
greetfunction that takes aPersonobject and prints a greeting using the object's attributes. - Creates an instance of
Personnamedpwith the name 'Madhu' and gender 'Male'. - Calls the
greetfunction with thepobject, resulting in the output: "Hi my name is Madhu and I am a Male".
Output
Example 17
Explanation
- Defines a function
greetthat takes apersonobject and prints a greeting using the person's name and gender. - Creates a new
Personobjectp1with the name 'Dadi' and gender 'Male' inside thegreetfunction. - Returns the
p1object from thegreetfunction. - Calls the
greetfunction with aPersonobjectp(name 'Madhu', gender 'Male') and stores the returned object inx. - Prints the name and gender of the returned
Personobjectx, which will output 'Dadi' and 'Male'.
Output
Example 18
Explanation
- Defines a function
greetthat takes apersonobject and prints its memory address and a greeting message including the person's name and gender. - Uses the
id()function to retrieve the unique identifier for thepersonobject and thepobject. - Creates an instance of the
Personclass with the name 'Madhu' and gender 'Male'. - Calls the
greetfunction with thepobject, which prints the memory address ofpand the greeting message. - Expected output includes the memory address of
pand the string "Hi my name is Madhu and I am a Male".
Output
Example 19
Explanation
- Defines a function
greetthat takes an objectpersonas an argument and modifies itsnameattribute. - Uses
print(id(person))to display the memory address of thepersonobject before modification. - Sets
person.nameto 'Dadi' and prints a greeting message including the modified name and thegenderattribute of theperson. - Creates an instance of
Personwith initial values 'Madhu' and 'Male', and prints its memory address. - After calling
greet(p), it prints the updatednameattribute of thepersonobject, which will now be 'Dadi'.
Output
Object ki mutability
Example 20
Explanation
- Defines a function
greetthat modifies thenameattribute of apersonobject to 'Dadi' and returns the modified object. - Creates an instance of
Personclass with initial name 'Madhu' and gender 'Male', storing it in variablep. - Prints the memory address (ID) of the original
pobject. - Calls the
greetfunction withp, storing the returned object inp1, which is the same object asp. - Prints the memory address of
p1(same asp) and the updatednameattribute ofp1, which will output 'Dadi'.
Output
Encapsulation
Encapsulation means hiding internal details of a class and only exposing what’s necessary. It helps to protect important data from being changed directly and keeps the code secure and organized.
Example 21
Explanation
- Defines a class
Personwith an initializer method__init__that takesname_inputandcountry_inputas parameters. - The
__init__method assigns the input values to instance variablesself.nameandself.country. - Creates two instances of the
Personclass:p1with name 'nitish' and country 'india', andp2with name 'steve' and country 'australia'. - No output is produced; the code simply initializes objects in memory.
Example 22
Explanation
- Accesses the
nameattribute of the objectp1. - Assumes
p1is an instance of a class that has anameattribute defined. - Returns the value stored in the
nameattribute, which could be a string or other data type. - If
p1does not have anameattribute, it will raise anAttributeError.
Output
Example 23
Explanation
- Accesses the
nameattribute of the objectp2. - Assumes
p2is an instance of a class that has anameattribute defined. - Returns the value stored in the
nameattribute, which could be a string or other data type. - If
p2does not have anameattribute, it will raise anAttributeError.
Output
Example 24
Explanation
- Defines an
Atmclass that simulates basic ATM functionalities like creating a PIN, changing it, checking balance, and withdrawing money. - The
__init__method initializes the ATM object with a default PIN and balance, and prints the object's memory address. - The
menumethod prompts the user for input to navigate through different ATM options and calls the corresponding methods based on user selection. - The
create_pin,change_pin,check_balance, andwithdrawmethods handle specific functionalities, including user input validation for PINs and balance checks. - The expected output includes success messages for actions taken, balance information, or error messages for invalid PINs or insufficient funds.
Example 25
Explanation
- Creates a new instance of an ATM class called 'obj'
- Uses the Atm() constructor to initialize the object
- No parameters are passed to the constructor
- This object will have all methods and attributes defined in the Atm class
- The variable 'obj' now references this newly created ATM instance
Output
Example 26
Explanation
- Calls the
create_pin()method on theobjinstance, which likely generates a new PIN code. - The method may involve logic to ensure the PIN meets certain criteria (e.g., length, complexity).
- It is expected to modify the state of
objby storing the newly created PIN. - The output or return value is not specified, but it may indicate success or failure of the PIN creation process.
Output
Example 27
Explanation
- Assigns the string value 'hehehehe' to the
balanceattribute of theobjobject. - This operation updates or creates the
balanceattribute if it does not already exist. - The
objmust be an instance of a class that allows dynamic attribute assignment. - No output is produced, but the state of
objis modified to include the newbalancevalue.
Example 28
Explanation
- Calls the
withdrawmethod on theobjinstance, which likely represents an object related to a financial account or resource management. - The
withdrawmethod typically reduces the balance or available amount in the account by a specified amount, though the amount is not shown in this snippet. - Expected output may include a change in the account balance, and it may also trigger an error if the withdrawal exceeds the available balance.
- This operation may also involve side effects such as logging the transaction or updating a user interface to reflect the new balance.
Output
Example 29
Explanation
- Defines an
Atmclass with a constructor that initializes a publicpinattribute and a private__balanceattribute. - Contains a private method
__menuthat prompts the user for actions like creating/changing a pin, checking balance, or withdrawing money. - Implements methods for creating a pin (
create_pin), changing a pin (change_pin), checking balance (check_balance), and withdrawing money (withdraw), each requiring the correct pin for access. - Uses private attributes (indicated by
__) to restrict direct access to the balance, enhancing data encapsulation. - The expected output includes prompts for user input and messages confirming actions like pin creation, balance checks, or withdrawal success/failure.
Example 30
Explanation
- Creates a new instance of an ATM class called 'obj'
- Uses the Atm() constructor to initialize the object
- No parameters are passed to the constructor
- This object will have all methods and attributes defined in the Atm class
- The variable 'obj' now references this newly created ATM instance
Output
Example 31
Explanation
- Calls the
create_pin()method on theobjinstance, likely to initialize or set a PIN for the object. - Directly assigns the string 'hehehe' to the
__balanceattribute ofobj, which is intended to be a private variable due to the double underscore prefix. - The assignment of a string to
__balancemay lead to unexpected behavior if__balanceis meant to hold a numeric value representing a balance. - No output is produced from these operations, but the state of
objis modified with a new PIN and a potentially incorrect balance value.
Output
Example 32
Explanation
- Calls the
withdrawmethod on theobjinstance, which likely represents an object related to a financial account or resource management. - The
withdrawmethod typically reduces the balance or available amount in the account by a specified amount, though the amount is not shown in this snippet. - Expected output may include a change in the account balance, and it may also trigger an error if the withdrawal exceeds the available balance.
- This operation may also involve side effects such as logging the transaction or updating a user interface to reflect the new balance.
Output
Example 33
Explanation
- Accesses the
__balanceattribute of theobjinstance, which is likely a private variable. - The double underscore prefix suggests name mangling, meaning it is intended to be accessed only within the class.
- If
objhas a__balanceattribute, it will return its value; otherwise, it may raise anAttributeError. - This code is typically used to retrieve the current balance in a banking or financial application context.
Output
Example 34
Explanation
- Accesses the private attribute
__balanceof the objectobj, which is likely part of a class related to ATM functionality. - The double underscore prefix indicates name mangling in Python, making the attribute less accessible from outside the class.
- This code retrieves the current balance value stored in the
__balanceattribute. - The expected output is the value of
__balance, which represents the amount of money available in the ATM account.
Output
Example 35
Explanation
- Calls the
create_pin()method on theobjinstance, which likely initializes or sets a PIN for an ATM or banking application. - Directly modifies the private attribute
__balanceof theobjinstance, setting it to the string 'hehehe', which is unconventional since balances are typically numeric. - The use of name mangling (with
__) indicates that__balanceis intended to be a private variable, suggesting encapsulation practices in the class design. - This code may lead to unexpected behavior or errors later in the program due to the inappropriate data type for a balance.
Output
Example 36
Explanation
- Calls the
withdrawmethod on theobjinstance, which likely represents an object related to a financial account or resource management. - The
withdrawmethod typically reduces the balance or available amount in the account by a specified amount, though the amount is not shown in this snippet. - Expected output may include a change in the account balance, and it may also trigger an error if the withdrawal exceeds the available balance.
- This operation may also involve side effects such as logging the transaction or updating a user interface to reflect the new balance.
Output
Example 37
Explanation
- Defines an
Atmclass that simulates an ATM with private attributes and methods for managing a user's pin and balance. - The constructor (
__init__) initializes the ATM object, setting a private balance and printing the object's ID. - Key methods include
create_pin,change_pin,check_balance, andwithdraw, which handle user interactions and balance management. - The private attribute
__balanceis manipulated throughget_balanceandset_balancemethods to enforce encapsulation. - The
__menumethod (not called in the provided code) is designed to guide user actions based on input, but is commented out, meaning the menu functionality is not currently active.
Example 38
Explanation
- Creates a new instance of an ATM class called 'obj'
- Uses the Atm() constructor to initialize the object
- No parameters are passed to the constructor
- This object will have all methods and attributes defined in the Atm class
- The variable 'obj' now references this newly created ATM instance
Output
Example 39
Explanation
- Calls the get_balance method on an object to retrieve current account balance
- Uses dot notation to access a method belonging to the object instance
- Likely returns a numeric value representing available funds or account total
- Method name suggests this is part of a financial or accounting class/interface
- No parameters are passed to the method, so it returns the balance as currently stored
Output
Example 40
Explanation
- Sets the balance attribute of the object 'obj' to 1000
- Uses the set_balance method to modify the object's balance property
- This is a typical setter method for managing account or wallet balances
- The object's internal state is updated to reflect the new balance value
- No return value is produced, this is a void method that modifies the object directly
Example 41
Explanation
- Calls the get_balance method on an object to retrieve current account balance
- Uses dot notation to access a method belonging to the object instance
- Likely returns a numeric value representing available funds or account total
- Method name suggests this is part of a financial or accounting class/interface
- No parameters are passed to the method, so it returns the balance as currently stored
Output
Example 42
Explanation
- Calls the set_balance method on an object with the string 'hehehehe' as argument
- Likely attempts to validate or store this string value as a balance amount
- May raise an error if the input is not a valid numeric balance format
- Could trigger internal validation logic that checks if input matches expected balance patterns
- Side effect depends on implementation but probably updates internal balance state or throws exception
Output
Example 43
Explanation
- Calls the get_balance method on an object to retrieve current account balance
- Uses dot notation to access a method belonging to the object instance
- Likely returns a numeric value representing available funds or account total
- Method name suggests this is part of a financial or accounting class/interface
- No parameters are passed to the method, so it returns the balance as currently stored
Output
Example 44
Explanation
- Creates a Person class with name and gender attributes, then makes three Person objects with different names and genders
- Stores these three Person objects in a list called L
- Prints the entire list showing memory addresses of the objects rather than their contents
- Iterates through the list and prints each person's name and gender attributes
- Output shows object memory locations followed by individual name/gender pairs on separate lines
Output
Example 45
Explanation
- Creates a Person class with name and gender attributes, then makes 3 Person objects with different names and genders
- Stores these 3 Person objects in a dictionary with keys 'p1', 'p2', and 'p3'
- Prints the entire dictionary showing all 3 Person objects stored inside it
- Iterates through the dictionary keys and prints each Person object's name attribute
- Output shows the dictionary representation followed by all 3 names printed on separate lines
Output
Static Variables (vs Instance variables)
Example 46
Explanation
- This code shows comments about object-oriented programming concepts in Python
- It explains the difference between instance variables (that change per object like name and balance) and static/class variables (that remain same like Bank ifsc)
- The comments indicate that instance variables must be defined inside a constructor method
- This is setting up foundational knowledge for creating bank account objects with unique identifiers
- The code suggests a class structure where each customer gets unique ID while sharing common bank information
Example 47
Explanation
- This code defines an ATM class that simulates basic banking operations like creating pins, changing pins, checking balance, and withdrawing money
- The
__init__method is a constructor that initializes instance variables (pin, balance, cid) and prints the object's memory address when an object is created - The
menumethod displays a text-based interface for users to choose different ATM operations through input prompts - Methods like
create_pin,change_pin,check_balance, andwithdrawhandle specific ATM functionalities with input validation using pin checks - Each method performs actions based on user input and updates the object's state (like balance) or shows information to the user
Example 48
Explanation
- Creates an instance of an Atm class and assigns it to variable c1
- Uses the Atm constructor to initialize a new ATM object
- No parameters are passed to the constructor
- This creates a single ATM instance that can be used to call ATM methods
- The variable c1 now references this ATM object in memory
Output
Example 49
Explanation
- Creates a new instance of an Atm class and assigns it to variable c2
- Uses the Atm constructor to initialize a fresh ATM object
- No parameters are passed to the constructor
- This creates an ATM object that can be used to call ATM methods
- The variable c2 now references this new ATM instance in memory
Output
Example 50
Explanation
- Creates a new instance of an ATM class called 'c3'
- Uses the Atm() constructor to initialize the object
- No parameters are passed to the constructor
- This creates an ATM object that can be used to perform banking operations
- The variable c3 now references this new ATM instance in memory
Output
Example 51
Explanation
- Prints the
cidattribute of three objects (c1, c2, c3) to the console - Uses the
print()function to display the value of each object'scidproperty - Likely shows unique identifier values assigned to each of the three objects
- The
cidattribute probably contains some kind of identifier like an ID number or hash - Output will display one cid per line, showing the specific identifier values for each object
Output
Example 52
Explanation
- This comment explains that static variables in Python are defined at the class level, outside of any method including the constructor (init)
- Static variables belong to the class itself rather than to any specific instance of the class
- These variables are shared among all instances of the class and maintain their value across all objects
- The constructor (init) is where instance variables are typically initialized for individual object instances
- This approach helps in creating class-level attributes that are consistent across all objects of the class
Example 53
Explanation
- Class
Atmdefines an ATM system with instance variables for pin, balance, and customer ID, along with static variablecounterto track number of accounts - Constructor
__init__initializes each ATM object with default values, assigns unique customer ID using static counter, and prints object's memory address - Private methods like
__menu,__balanceandset_balancecontrol access to sensitive data and provide menu-driven interface for ATM operations - Public methods handle core ATM functionality including creating/changing pins, checking balance, and withdrawing money with proper validation
- Balance is stored as private variable
__balancewith getter/setter methods to ensure data integrity and prevent direct access from outside the class
Example 54
Explanation
- Creates three separate instances of an Atm class using the constructor
- Each variable (c1, c2, c3) holds a unique object with its own state and properties
- The Atm() constructor is called three times to initialize three different ATM machines
- Each instance would have independent data and methods when used later in the code
- No output is produced at this stage since we're only creating objects, not calling methods
Output
Example 55
Explanation
- Prints the
cidattribute of three objects (c1, c2, c3) to the console - Uses the
print()function to display the value of each object'scidproperty - Likely shows unique identifier values assigned to each of the three objects
- The
cidattribute probably contains some kind of identifier like an ID number or hash - Output will display one cid per line, showing the specific identifier values for each object
Output
Example 56
Explanation
- Accesses the counter attribute of the Atm class to retrieve its current value
- This is a class-level attribute that likely tracks the number of ATM instances created
- The counter variable is probably initialized to 0 and incremented each time an ATM object is instantiated
- Returns the integer value representing how many ATM objects have been created so far
- No side effects occur when reading this attribute, it simply returns the stored count value
Output
Example 57
Explanation
- Sets a class attribute named
counteron theAtmclass to the string value'hehehe' - This modifies the
Atmclass itself rather than creating an instance attribute - The assignment happens at the class level, so all instances of
Atmwill share this attribute - No functions or methods are called, this is a simple attribute assignment
- This changes the class state permanently until overwritten by another assignment
Example 58
Explanation
- Creates a new instance of an ATM class called 'c4'
- Uses the Atm() constructor to initialize the object
- No parameters are passed to the constructor
- This creates an ATM object that can be used to perform banking operations
- The variable c4 now references this new ATM instance in memory
Output
Example 59
Explanation
- This code defines an ATM class with private attributes like balance and pin, and a static counter to track instance IDs
- The constructor (
__init__) initializes each ATM object with empty pin, zero balance, and a unique ID from the static counter - Private methods like
__menu,create_pin,change_pin,check_balance, andwithdrawhandle user interactions and operations - Getters and setters are used to access and modify the private balance attribute safely
- The menu system guides users through various ATM functions using input validation and conditional logic
Example 60
Explanation
- Creates three separate instances of an Atm class using the constructor
- Each variable (c1, c2, c3) holds a unique object with its own state and properties
- The Atm() constructor is called three times to initialize three different ATM machines
- Each instance would have independent data and methods when used later in the code
- No output is produced at this stage since we're only creating objects, not calling methods
Output
Example 61
Explanation
- Prints the
cidattribute of three objects (c1, c2, c3) to the console - Uses the
print()function to display the value of each object'scidproperty - Likely shows unique identifier values assigned to each of the three objects
- The
cidattribute probably contains some kind of identifier like an ID number or hash - Output will display one cid per line, showing the specific identifier values for each object
Output
Example 62
Explanation
- This code accesses a private class variable
__counterfrom theAtmclass using Python's name mangling feature - The double underscore prefix (
__) in__countertriggers Python's name mangling mechanism that changes the variable name internally - Name mangling makes the variable harder to access directly from outside the class by prefixing it with
_ClassName - The code demonstrates how to access mangled names using the pattern
_ClassName__variable_name - This reveals the internal counter value that was intended to be private and encapsulated within the class
Output
Static Methods
Example 63
Explanation
- This code defines an ATM class with private attributes like balance and pin, and a static counter to track object creation
- The constructor (
__init__) initializes each ATM instance with empty pin, zero balance, and a unique customer ID from the static counter - Private methods like
__menuhandle user interactions through input prompts and call other methods based on user choices - Public methods allow users to create/change pins, check balance, and withdraw money while validating inputs and pin authentication
- Static method
get_counterprovides access to the class-level counter that tracks how many ATM objects have been created
Example 64
Explanation
- Creates an instance of an Atm class and assigns it to variable c1
- Uses the Atm constructor to initialize a new ATM object
- No parameters are passed to the constructor
- This creates a single ATM instance that can be used to call ATM methods
- The variable c1 now references this ATM object in memory
Output
Example 65
Explanation
- Calls the get_counter() method on the c1 object to retrieve its current counter value
- This is likely a custom class method that returns an integer representing a count
- The operation has no side effects - it only reads and returns the current counter state
- Expected output is the numeric value of the counter stored in the c1 object
- Key API used is the method call syntax .get_counter() on an object instance
Output
Example 66
Explanation
- Calls the get_counter() method on the Atm class to retrieve a counter value
- Likely returns a numeric count or timestamp from an ATM system's internal tracking mechanism
- This is a class method call that doesn't require instance creation since it's accessed directly from the class
- Commonly used to track transaction numbers, session counts, or system metrics in banking applications
- Output would be the current value of whatever counter the ATM system is maintaining internally
Output
###Q1:Count number of instances of a class created in Python?
Example:
Say Car is any class.
So after creating above instances. We want to count how many instances are created of Car class.
For above example no of instances = 3.
Write a program for above problem.
Example 67
Explanation
- Creates a Car class with a private class variable
__counterthat tracks number of instances - Constructor (
__init__) increments the counter each time a new Car object is created - Defines a class method
get_counterthat returns the current value of the counter - Four Car objects are instantiated, causing the counter to increment from 0 to 4
- Prints the final counter value, which is 4, representing the total number of Car instances created
Output
###Q-2: Create a deck of cards class. Internally, the deck of cards should use another class, a card class. Your requirements are:
- The
Deckclass should have a deal method to deal a single card from the deck - After a card is dealt, it is removed from the deck.
- There should be a shuffle method which makes sure the deck of cards has all 52 cards and then rearranges them randomly.
- The Card class should have a suit (Hearts, Diamonds, Clubs, Spades) and a value (A,2,3,4,5,6,7,8,9,10,J,Q,K)
Deck Class
- It is class of all possible cards in a deck. Total 52 cards.
- Methods -
deal()it will take out one card from the deck of cards. - Deck of cards should get shuffeled while creating the deck object.
no of cards remaining in deck - <number>should dsiplay on printing any deck object.
Card class
- It is a class of card
- Atrributes -
suitandvalue <suit> of <value>should dsiplay on printing any card object.
Example 68
Explanation
- Creates a card class to represent individual playing cards with suit and value attributes, and a string representation method
- Creates a deck class that initializes a full 52-card deck using list comprehension with all combinations of suits and values
- Implements shuffle method that only works on full decks and uses random.shuffle to reorder cards
- Implements deal method that removes and returns the last card from the deck, with error handling for empty decks
- Prints two dealt cards followed by the remaining card count in the deck after shuffling
Output
Q-3: Find the area of a rectangle.
Approach:
- The class name should be Rectangle.
- The constructor should accept two parameters length and height but you can't pass the values directly to it while creating the constructor. E.g., rectangle = Rectangle(length=10, height=8) <-- you can't do that while creating the instances.
- Create a method called area() which has no parameters.
- Create a method called is_square() which also has no parameters. Return True if the rectangle is a square otherwise return False.
- If you are using a if-else block inside the is_square() method, then use the one-linear syntax.
Example 69
Explanation
- Creates a Rectangle class with length and breadth attributes initialized through
__init__ - Uses
@classmethoddecorator to define a class methodpropertythat creates new Rectangle instances - Calls
Rectangle.property(4,4)to create a rectangle with equal length and breadth - Calculates and prints the area of the rectangle (16) and checks if it's a square (True)
- The class method allows creating objects without directly calling the constructor with different syntax
Output
Q-4: Problem 4
Statement: Write a program that uses datetime module within a class. Enter manufacturing date and expiry date of the product. The program must display the years, months and days that are left for expiry.
Example 70
Explanation
- Creates a Product class that asks user for manufacturing and expiry dates in MM/DD/YYYY format
- Uses datetime.strptime to convert string dates into datetime objects for proper date manipulation
- Implements time_to_expire method that compares current date with expiry date
- Prints "product expired already" if current date is past expiry date
- Shows remaining days until expiration using date subtraction when product is still valid
Output
Q-5: Problem 5
Statement: A university wants to automate their admission process. Students are admitted based on the marks scored in the qualifying exam. A student is identified by student id, age and marks in qualifying exam. Data are valid, if:
- Age is greater than 20
- Marks is between 0 and 100 (both inclusive)
A student qualifies for admission, if
- Age and marks are valid and
- Marks is 65 or more
Write a python program to represent the students seeking admission in the university. The details of student class are given below.
Example 71
Explanation
- Defines a
Studentclass with private attributes for student ID, marks, and age, initialized toNone. - Includes setter methods to assign values to the private attributes and getter methods to retrieve their values.
- Contains validation methods to check if the age is greater than 20 and if marks are within the range of 0 to 100.
- The
check_qualificationmethod determines if the student is qualified based on age and marks, returningTrueif marks are 65 or above. - Creates an instance of
Student, sets its attributes, and prints the student ID, marks, and age, but does not print the qualification result.
Output
###Q-6: Ice-Cream Scoops and Bowl shop
-
Create a class
Scoopwhich has one public propertyflavorand one private propteryprice. Takeflavorvalues during object creation. -
Create a class
Bowlwith private prpertyscoop_listwhich will have list of scoopd object. -
Create a method
add_scoopsinBowlclass which will add any no ofScoopobjects given as parameter and store it inscoops_list. -
Make getter and setter method for
priceproperty. -
Make a method
displayto displayflavourandpriceof each in and print total price of the bowl by adding all flavour scoops prices.
Ex.-
Output
Example 72
Explanation
- Defines two classes:
Scoopfor ice cream scoops andBowlfor holding multiple scoops. Scooptracks the number of instances created with a class variable__counter, and has methods to set/get the price and a string representation.Bowlalso tracks its instances with a class variable__counter, allows adding multipleScoopinstances, and displays the total price of all scoops.- The
soldstatic method in both classes returns the number of instances created, providing a way to track how many scoops and bowls have been sold. - The expected output includes printed details of each scoop's flavor and price, along with the total price when
Bowl.display()is called.
Example 73
Explanation
- Creates three
Scoopobjects for chocolate, berry, and vanilla flavors, each with a specific price set using theset_pricemethod. - Initializes a
Bowlobject and adds the scoops to it using theadd_scoopsmethod, which can accept both single and multiple scoop parameters. - Calls the
displaymethod on thebowlobject to show the contents of the bowl, likely including the flavors and their prices. - Prints the total number of scoops sold and the total number of bowls sold by calling the
soldclass methods onScoopandBowlclasses, respectively.
Output
###Q-7:Ice-Cream Bowl continue..
Making advancement in the above classes. Scoop and Bowl
-
Introduce a property
max_scoopsinBowlclass to signify maximum scoops that a bowl can have, exceeding that it will displayBowl is full. Take default value as3. -
no_of_scoopinScoopclass with default value of1 -
Print
<flavour> addedwith every scoop added.
Output:
Testing code-2 considering above test code executed
Output
Testing code-3, considering above tests executed
Output:
Example 74
Explanation
- Defines two classes,
ScoopandBowl, to model ice cream scoops and bowls that hold them. Scoopclass has methods to set and get the price of a scoop, and a static method to count total scoops created.Bowlclass can hold multiple scoops, with a method to add scoops and check if the bowl is full, and a method to display all scoops and their total price.- Uses private attributes (e.g.,
__price,__scoop_list) to encapsulate data and prevent direct access from outside the class. - Expected output includes messages when scoops are added or when the bowl is full, and displays the flavor and price of each scoop along with the total price when displayed.
Example 75
Explanation
- Creates instances of a
Scoopclass for different ice cream flavors (chocolate, berry, vanilla) and sets their prices. - Uses the
set_pricemethod to assign a price to each scoop and prints the scoop details. - Initializes a
Bowlinstance to hold scoops, using default parameters for maximum scoops. - Adds the chocolate and berry scoops individually, and the vanilla scoop alongside the berry scoop in a single call.
- Calls the
displaymethod on the bowl to show the contents and details of the scoops added.
Output

