Skip to content
Cover image for: Encapsulation & Static Keyword in Python
#pythonBeginner

Encapsulation & Static Keyword in Python

May 5, 2026
Updated May 14, 2026
30 min read

AI Insights

Powered by GPT-4o-mini

Verified Context: encapsulation-static-keyword-in-python

Learn encapsulation and static members in Python OOP. Understand how name mangling with double underscore prefixes provides weak encapsulation, the @property decorator pattern for controlled attribute access with validation, @staticmethod for utility functions that do not depend on instance state, @classmethod for factory methods and alternative constructors, and practical examples including a Point class for 2D coordinate geometry with distance calculations and origin reference.

Quick Summary

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.

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

Python class implementation for geometric point and line operations with distance calculations

Explanation

  • The Point class represents 2D coordinates with methods to calculate Euclidean distance between points and distance from origin using the Pythagorean theorem
  • The Line class models linear equations in standard form (Ax + By + C = 0) with functionality to determine if points lie on the line and calculate shortest distances from points to lines
  • Both classes include string representation methods for easy visualization of their mathematical objects
  • The euclidean_distance method implements the distance formula derived from the Pythagorean theorem for calculating straight-line distances between two coordinate points
  • The shortest_distance method uses the standard formula for point-to-line distance in coordinate geometry, involving absolute value and square root calculations
python

Demonstrating point and line object initialization and display in Python geometry classes

Explanation

  • Two Point objects are created with coordinates (1, 2) and (3, 4) respectively, demonstrating basic object instantiation
  • A Line object is initialized with parameters (3, 4, 5) which likely represents slope and intercept values
  • The print statements show how these custom objects are displayed when converted to string representation
  • This code illustrates the typical usage pattern of geometric class objects in Python programming
  • The output would display the string representations of the Point and Line objects as defined in their respective str methods
python

Output

text

Calculate the Euclidean distance between two points using a method from a point class.

Explanation

  • The method euclidean_distance is called on an instance p1, which likely represents a point in a multi-dimensional space.
  • The argument p2 is another point instance, indicating that the distance between p1 and p2 is being computed.
  • This function typically uses the formula for Euclidean distance, which involves calculating the square root of the sum of the squared differences between corresponding coordinates of the two points.
  • The result of this method is a numerical value representing the straight-line distance between the two points in the defined space.
  • This functionality is commonly used in various applications, including machine learning, physics simulations, and geometric calculations.
python

Output

text

Calculate the distance of a point from the origin in a 2D space using a method call.

Explanation

  • The code snippet calls the distance_from_origin() method on an object p1, which is likely an instance of a class representing a point in a 2D coordinate system.
  • This method computes the Euclidean distance from the point p1 to the origin (0, 0) using the formula √(x² + y²), where x and y are the coordinates of the point.
  • The result of this method call is typically a numeric value representing the distance, which can be used for further calculations or comparisons.
  • Ensure that the p1 object is properly initialized with its coordinates before invoking this method to avoid errors.
python

Output

text

This code demonstrates the usage of a Line and Point class to analyze geometric relationships.

Explanation

  • A Line object is created with parameters representing its coefficients, while a Point object is instantiated with specific coordinates.
  • The print statements output the string representations of the Line and Point objects, showcasing their details.
  • The method point_on_line(p1) checks if the point p1 lies on the line l1, returning a boolean result.
  • The method shortest_distance(p1) calculates the shortest distance from the point p1 to the line l1, providing a numerical value.
  • Additional checks are performed with another Point object to determine if it lies on the line and to calculate its distance from the line.
python

Output

text

How objects access attributes

This code defines a Person class that customizes greetings based on the country of the individual.

Explanation

  • The Person class initializes with two attributes: name and country, set through the __init__ method.
  • The greet method checks the value of the country attribute to determine the appropriate greeting.
  • If the country is 'india', it prints a greeting in Hindi ("Namaste"), otherwise it defaults to a standard English greeting ("Hello").
  • This structure allows for easy extension to include more countries and their respective greetings in the future.
python

Creating an instance of a Person class with attributes for name and country

Explanation

  • The code initializes a new object p of the Person class.
  • The constructor of the Person class is called with two arguments: 'Madhu' for the name and 'India' for the country.
  • This instance p will have attributes that can be accessed later, representing the provided values.
  • The code assumes that the Person class is defined elsewhere in the program.
python

Accessing the 'name' attribute of an object in Python

Explanation

  • This code snippet retrieves the value of the 'name' attribute from an object referenced by the variable 'p'.
  • The 'p' variable is expected to be an instance of a class that has a defined 'name' attribute.
  • Accessing attributes in Python is done using dot notation, which allows for easy retrieval of object properties.
  • If 'p' does not have a 'name' attribute, this code will raise an AttributeError.
python

Output

text

Accessing methods of an object in Python

Explanation

  • The code snippet calls the greet() method on an instance of an object p.
  • This demonstrates how to invoke methods that are defined within a class.
  • The method greet() is expected to perform a specific action, such as printing a greeting message.
  • Ensure that the object p is properly instantiated from a class that includes the greet() method.
python

Output

text

Understanding AttributeError when Accessing Non-Existent Attributes in Python

Explanation

  • The code attempts to access the gender attribute of the object p.
  • If p does not have a gender attribute defined, Python will raise an AttributeError.
  • This error indicates that the requested attribute is not found in the object's namespace.
  • It's important to handle such cases to prevent program crashes, often using hasattr() or try-except blocks.
python

Output

text

Attribute creation from outside of the class

This code assigns the gender attribute of an object to 'Male'.

Explanation

  • The code sets the gender attribute of the object p to the string value 'Male'.
  • This operation modifies the state of the object p, which is likely an instance of a class that has a gender attribute.
  • The assignment is straightforward and follows Python's dynamic typing, allowing for easy modification of object properties.
python

Accessing the gender attribute of an object in Python

Explanation

  • This code snippet retrieves the value of the gender attribute from an object p.
  • It assumes that p is an instance of a class that has a defined gender attribute.
  • The attribute can hold various data types, such as strings or enums, representing the gender.
  • This is a common practice in object-oriented programming to access properties of an object.
  • Ensure that the object p is properly instantiated and the gender attribute exists to avoid errors.
python

Output

text

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

Understanding Object References in Python with a Simple Class Definition

Explanation

  • A Person class is defined with an __init__ method that initializes two attributes: name and gender.
  • An instance of the Person class is created and assigned to the variable p, which holds a reference to the object in memory.
  • The variable q is then assigned the same reference as p, meaning both p and q point to the same Person object.
  • This demonstrates how variables in Python store references to objects rather than the objects themselves.
python

This code snippet demonstrates how to retrieve and display the memory addresses of two variables in Python.

Explanation

  • The id() function is used to obtain the unique identifier (memory address) of an object in Python.
  • The print() function outputs the memory addresses of the variables p and q to the console.
  • This can be useful for understanding object identity and whether two variables reference the same object in memory.
  • The output will be different for each run unless the variables point to the same object.
python

Output

text

Python object attribute manipulation and reference behavior demonstration

Explanation

  • The code demonstrates how object attributes work when variables reference the same object instance
  • Initially prints the name attribute of two objects p and q, showing their current values
  • Modifies the name attribute of object q and shows that both objects reflect the same value change
  • Illustrates that p and q likely reference the same object instance rather than independent copies
  • Demonstrates the concept of object references and mutable attribute modification in Python
python

Output

text

Pass by reference

This code defines a Person class and a function to greet the person with their name and gender.

Explanation

  • A Person class is created with an __init__ method that initializes the name and gender attributes.
  • The greet function takes a Person object as an argument and prints a greeting that includes the person's name and gender.
  • An instance of the Person class is created with the name 'Madhu' and gender 'Male'.
  • The greet function is called with the Person instance, resulting in a personalized greeting being printed to the console.
python

Output

text

This code defines a function to greet a person and returns a new Person object.

Explanation

  • The greet function takes a person object as an argument and prints a greeting message including the person's name and gender.
  • Inside the function, a new Person object p1 is created with the name 'Dadi' and gender 'Male', which is then returned.
  • An instance of Person named p is created with the name 'Madhu' and gender 'Male', which is passed to the greet function.
  • After calling greet, the returned object x is printed to display the name and gender of the newly created Person object p1.
  • This code demonstrates object-oriented programming by utilizing a class (assumed to be defined elsewhere) to create and manipulate person objects.
python

Output

text

This code defines a function to greet a person and display their memory address.

Explanation

  • The greet function takes a person object as an argument and prints its memory address using id(person).
  • It then prints a greeting message that includes the person's name and gender attributes.
  • A Person object named p is created with the name 'Madhu' and gender 'Male'.
  • The memory address of the Person object p is printed before calling the greet function.
  • The greet function is invoked with p, displaying both the memory address and the greeting message.
python

Output

text

This code demonstrates how to modify an object's attributes in Python using a function.

Explanation

  • The greet function takes a person object as an argument and prints its memory address using id().
  • It modifies the name attribute of the person object to 'Dadi'.
  • The function then prints a greeting message that includes the modified name and the gender attribute of the person object.
  • An instance of Person is created with the name 'Madhu' and gender 'Male', and its memory address is printed before calling greet().
  • After calling greet(), the modified name of the person object is printed, showing that the change persists outside the function.
python

Output

text

Object ki mutability

This code demonstrates how a function modifies an object's attribute and returns the same object reference.

Explanation

  • The greet function takes an object person as an argument and sets its name attribute to 'Dadi'.
  • A Person object p is created with the name 'Madhu' and gender 'Male'.
  • The id function is used to print the memory address of the original object p.
  • The greet function is called with p, and the returned object p1 is the same as p, as it modifies the original object.
  • Finally, the modified name of p1 is printed, showing 'Dadi' as the updated value.
python

Output

text

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.

Creating and initializing instances of a Person class in Python

Explanation

  • Defines a Person class with an __init__ method to initialize instance variables.
  • The __init__ method takes two parameters: name_input and country_input, which are assigned to instance variables self.name and self.country.
  • Two instances of the Person class are created: p1 with the name 'nitish' from 'india' and p2 with the name 'steve' from 'australia'.
  • This structure allows for the creation of multiple Person objects with unique attributes.
python

Accessing the 'name' attribute of an object in Python

Explanation

  • This code snippet retrieves the value of the 'name' attribute from an object referenced by the variable 'p1'.
  • It assumes that 'p1' is an instance of a class that has a defined 'name' attribute.
  • The output will be the current value stored in 'p1.name', which could be a string or any other data type depending on the class definition.
python

Output

text

Accessing the 'name' attribute of an object in Python

Explanation

  • This code snippet retrieves the value of the 'name' attribute from the object referenced by the variable 'p2'.
  • It assumes that 'p2' is an instance of a class that has a defined 'name' attribute.
  • The output will depend on the specific value assigned to 'p2.name' during the object's initialization or modification.
  • This is a common practice in object-oriented programming to access properties of an object.
python

Output

text

A simple ATM class implementation in Python for managing user PIN and balance operations

Explanation

  • Defines an Atm class with methods for creating, changing, and checking a PIN, as well as checking the balance and withdrawing funds.
  • The __init__ method initializes the ATM object with a default PIN and balance, automatically executed upon object instantiation.
  • The menu method prompts the user for input to navigate through various ATM functionalities.
  • Each operation (create, change, check balance, withdraw) is handled by its respective method, ensuring modularity and clarity.
  • User input is validated against the stored PIN to secure sensitive operations like balance checking and withdrawals.
python

Instantiating an ATM object in Python for banking operations

Explanation

  • The code creates an instance of the Atm class, which likely encapsulates functionality related to automated teller machine operations.
  • The variable obj now holds a reference to this newly created Atm object, allowing access to its methods and properties.
  • This instantiation is essential for performing actions such as checking balances, withdrawing cash, or depositing funds through the ATM interface.
python

Output

text

This code snippet invokes a method to create a new pin for an object.

Explanation

  • The create_pin() method is called on the obj instance, suggesting that obj is an instance of a class that has this method defined.
  • This method likely handles the logic for generating or initializing a pin, which could be used for security or identification purposes.
  • The absence of parameters in the method call indicates that it may use default values or internal logic to create the pin.
  • The method's execution may involve updating the state of obj or returning a value, although this is not shown in the snippet.
python

Output

text

This code assigns a string value to the balance attribute of an object.

Explanation

  • The code sets the balance attribute of the obj instance to the string 'hehehehe'.
  • This could be part of a larger class where balance is expected to hold numerical values, indicating a potential type mismatch.
  • It demonstrates dynamic attribute assignment in Python, where attributes can be added or modified at runtime.
  • The use of a string for a balance may lead to errors in calculations if not handled properly later in the code.
python

This code snippet invokes the withdraw method on an object to perform a withdrawal action.

Explanation

  • The withdraw() method is called on the obj instance, indicating that obj likely represents a financial account or similar entity.
  • This method typically handles the logic for deducting a specified amount from the account balance.
  • The implementation of withdraw() may include checks for sufficient funds and may raise exceptions if the withdrawal cannot be completed.
  • The code assumes that obj has been properly initialized and that the withdraw() method is defined within its class.
python

Output

text

Implementing a Simple ATM Class with Private Attributes in Python

Explanation

  • The Atm class simulates an ATM system with functionalities such as creating and changing a PIN, checking balance, and withdrawing money.
  • The constructor __init__ initializes public and private attributes, where self.pin is public and self.__balance is a private attribute, inaccessible from outside the class.
  • The __menu method provides a user interface for interacting with the ATM, allowing users to select various options through input.
  • Methods like create_pin, change_pin, check_balance, and withdraw implement the core functionalities, ensuring that actions are only performed if the correct PIN is provided.
  • The use of double underscores for __balance enforces encapsulation, preventing direct access to the balance from outside the class, enhancing security.
python

Instantiating an ATM object in Python for banking operations

Explanation

  • The code creates an instance of the Atm class, which likely encapsulates functionality related to automated teller machine operations.
  • The variable obj now holds a reference to this newly created Atm object, allowing access to its methods and properties.
  • This instantiation is essential for performing actions such as checking balances, withdrawing cash, or depositing funds through the ATM interface.
python

Output

text

This code snippet demonstrates the creation of a pin and attempts to set a private attribute in a Python object.

Explanation

  • The method create_pin() is called on the object obj, which likely initializes or generates a pin for the user.
  • The line obj.__balance = 'hehehe' attempts to set a private attribute __balance to the string 'hehehe', which is not a recommended practice for managing sensitive information.
  • The use of double underscores before balance indicates name mangling, meaning it will be stored as _obj__balance, making it less accessible from outside the class.
  • This snippet may indicate a misunderstanding of encapsulation, as directly assigning to a private attribute can lead to unintended consequences.
python

Output

text

This code snippet invokes the withdraw method on an object to perform a withdrawal action.

Explanation

  • The withdraw() method is called on the obj instance, indicating that obj likely represents a financial account or similar entity.
  • This method typically handles the logic for deducting a specified amount from the account balance.
  • The implementation of withdraw() may include checks for sufficient funds and may raise exceptions if the withdrawal cannot be completed.
  • The code assumes that obj has been properly initialized and that the withdraw() method is defined within its class.
python

Output

text

Accessing the private balance attribute of an object in Python

Explanation

  • The code snippet attempts to access the __balance attribute of an object named obj.
  • The double underscore prefix indicates that __balance is intended to be a private attribute, following Python's name mangling convention.
  • Direct access to private attributes is generally discouraged as it breaks encapsulation principles.
  • This access may raise an AttributeError if the attribute does not exist or if it is not accessible due to its private nature.
python

Output

text

Accessing a private attribute in a Python class using name mangling

Explanation

  • The code snippet accesses a private attribute __balance of an object obj through name mangling.
  • In Python, attributes prefixed with double underscores are considered private and are not directly accessible from outside the class.
  • Name mangling changes the name of the attribute to _Atm__balance, allowing access to it from outside the class.
  • This technique is generally discouraged as it breaks encapsulation principles, but it can be useful for debugging or specific use cases.
python

Output

text

This code snippet demonstrates how to create a pin and manipulate a private attribute in a Python class.

Explanation

  • The create_pin() method is called on the obj instance, which likely initializes or sets a PIN for an ATM or similar application.
  • The line obj._Atm__balance = 'hehehe' directly accesses and modifies a private attribute __balance of the Atm class, which is typically not recommended as it breaks encapsulation.
  • The use of a string 'hehehe' suggests that the balance is being set to an invalid or placeholder value, which may lead to unexpected behavior in the application.
  • This code highlights the importance of understanding Python's name mangling for private attributes, as accessing them directly can lead to maintenance issues.
python

Output

text

This code snippet invokes the withdraw method on an object to perform a withdrawal action.

Explanation

  • The withdraw() method is called on the obj instance, indicating that obj likely represents a financial account or similar entity.
  • This method typically handles the logic for deducting a specified amount from the account balance.
  • The implementation of withdraw() may include checks for sufficient funds and may raise exceptions if the withdrawal cannot be completed.
  • The code assumes that obj has been properly initialized and that the withdraw() method is defined within its class.
python

Output

text

Implementing a Secure ATM Class with Private Attributes in Python

Explanation

  • The Atm class encapsulates ATM functionalities, including creating and managing a user PIN and balance.
  • The constructor (__init__) initializes the ATM object, setting the initial balance to zero and defining a private attribute for balance using double underscores.
  • The get_balance and set_balance methods provide controlled access to the private balance attribute, ensuring that only integers can be set as the balance.
  • The __menu method (private) prompts users for actions like creating or changing a PIN, checking balance, and withdrawing funds, enhancing user interaction.
  • Security is enforced by requiring the correct PIN for balance checks and withdrawals, preventing unauthorized access to sensitive information.
python

Instantiating an ATM object in Python for banking operations

Explanation

  • The code creates an instance of the Atm class, which likely encapsulates functionality related to automated teller machine operations.
  • The variable obj now holds a reference to this newly created Atm object, allowing access to its methods and properties.
  • This instantiation is essential for performing actions such as checking balances, withdrawing cash, or depositing funds through the ATM interface.
python

Output

text

This code retrieves the current balance of a financial object or account.

Explanation

  • The method get_balance() is called on an object named obj, which likely represents a financial account or similar entity.
  • It is expected to return the current balance, which could be a numeric value representing currency.
  • The method may involve internal logic to access and compute the balance from stored data.
  • This operation is typically used in banking applications or financial management systems to display account status.
python

Output

text

This code sets the balance of an object to a specified value.

Explanation

  • The method set_balance is called on the object obj.
  • It takes a single argument, 1000, which represents the new balance to be set.
  • This operation likely updates an internal attribute of the object to reflect the new balance.
  • The method is expected to handle any necessary validation or state changes related to the balance update.
python

This code retrieves the current balance of a financial object or account.

Explanation

  • The method get_balance() is called on an object named obj, which likely represents a financial account or similar entity.
  • It is expected to return the current balance, which could be a numeric value representing currency.
  • The method may involve internal logic to access and compute the balance from stored data.
  • This operation is typically used in banking applications or financial management systems to display account status.
python

Output

text

Setting an invalid balance value using a setter method in Python object-oriented programming

Explanation

  • The code calls a set_balance method on an object instance, passing a string value 'hehehehe' instead of a numeric balance amount
  • This demonstrates a potential issue with input validation where non-numeric data is accepted by the setter method
  • The operation likely triggers internal validation logic that may either reject the invalid input or convert it to a numeric value
  • This pattern shows how object-oriented methods can encapsulate state management while potentially exposing vulnerabilities in data type handling
  • Such code might be part of a banking or financial application where proper input validation is crucial for maintaining data integrity
python

Output

text

This code retrieves the current balance of a financial object or account.

Explanation

  • The method get_balance() is called on an object named obj, which likely represents a financial account or similar entity.
  • It is expected to return the current balance, which could be a numeric value representing currency.
  • The method may involve internal logic to access and compute the balance from stored data.
  • This operation is typically used in banking applications or financial management systems to display account status.
python

Output

text

Creating and managing a list of Person objects in Python

Explanation

  • Defines a Person class with attributes name and gender initialized through the constructor.
  • Instantiates three Person objects with different names and genders.
  • Stores the created Person objects in a list L.
  • Prints the entire list of Person objects.
  • Iterates through the list to print each person's name and gender.
python

Output

text

Creating and accessing a dictionary of custom objects in Python

Explanation

  • A Person class is defined with an __init__ method that initializes name and gender attributes.
  • Three instances of the Person class are created: p1, p2, and p3, representing different individuals.
  • These instances are stored in a dictionary d with string keys corresponding to each person.
  • The dictionary is printed to display the stored Person objects.
  • A loop iterates through the dictionary keys, printing the name attribute of each Person object.
python

Output

text

Static Variables (vs Instance variables)

Understanding the distinction between instance and static variables in Python classes

Explanation

  • The code comments highlight the importance of unique customer IDs for identification purposes.
  • It differentiates between instance variables, which can change (like name and balance), and static variables, which remain constant (like Bank IFSC).
  • Instance variables are defined within the constructor method, ensuring they are tied to specific instances of the class.
  • This structure allows for flexibility in managing individual customer data while maintaining fixed attributes across all instances.
python

A Python ATM Class for Managing User Transactions and PIN Security

Explanation

  • Defines an Atm class that simulates an ATM with functionalities like creating and changing a PIN, checking balance, and withdrawing money.
  • The constructor initializes attributes such as pin, balance, and a customer ID (cid), and automatically executes upon object creation.
  • The menu method presents options to the user and directs them to the appropriate functionality based on their input.
  • Methods like create_pin, change_pin, check_balance, and withdraw handle specific tasks, ensuring user input is validated against the stored PIN.
  • The program exits if the user inputs anything other than the specified options in the menu.
python

Instantiating an ATM object in Python for financial transactions

Explanation

  • The code creates an instance of the Atm class, which likely represents an Automated Teller Machine.
  • The variable c1 holds the reference to this newly created Atm object, allowing access to its methods and properties.
  • This instantiation is essential for performing operations such as withdrawals, deposits, or balance inquiries associated with the ATM functionality.
python

Output

text

Instantiating an ATM object in Python for banking operations

Explanation

  • The code creates an instance of the Atm class and assigns it to the variable c2.
  • This instance can be used to access methods and properties defined within the Atm class, allowing for operations related to automated teller machine functionalities.
  • The Atm class is expected to encapsulate behaviors such as withdrawing cash, checking balance, and depositing funds.
python

Output

text

This code snippet demonstrates the instantiation of an ATM class in Python.

Explanation

  • The variable c3 is created to hold an instance of the Atm class.
  • The Atm class likely contains methods and properties related to automated teller machine functionalities.
  • This instantiation allows the programmer to access and utilize the methods defined within the Atm class through the c3 object.
  • The code assumes that the Atm class is defined elsewhere in the codebase.
python

Output

text

Accessing the 'cid' attribute of multiple objects in Python

Explanation

  • The code prints the 'cid' attribute from three different objects: c1, c2, and c3.
  • Each object is expected to be an instance of a class that has a 'cid' attribute defined.
  • This snippet is useful for debugging or displaying the unique identifiers of these objects.
  • The output will show the values of 'cid' for each object sequentially in the console.
python

Output

text

Understanding the declaration of static variables in Python class definitions

Explanation

  • Static variables are defined outside of any instance methods, typically at the class level.
  • They are shared across all instances of the class, meaning they retain their value between instances.
  • This allows for data that is common to all instances to be stored in a single location, reducing memory usage.
  • Static variables can be accessed using the class name or through an instance of the class.
  • They are useful for constants or configuration settings that should not change per instance.
python

A Python class for simulating an ATM with basic banking operations

Explanation

  • Defines an Atm class that manages ATM functionalities such as creating and changing a PIN, checking balance, and withdrawing money.
  • Utilizes a static variable counter to assign a unique customer ID (cid) to each ATM instance.
  • Implements encapsulation by using a private variable __balance to store the account balance, ensuring it can only be modified through designated methods.
  • Provides a user interface through the __menu method, guiding users to perform various actions based on their input.
  • Includes error handling for invalid inputs, such as incorrect PINs and non-integer balance values.
python

Creating multiple instances of an ATM class in Python

Explanation

  • This code snippet initializes three separate instances of the Atm class, named c1, c2, and c3.
  • Each instance represents an independent object, allowing for separate states and behaviors.
  • The Atm class must be defined elsewhere in the code, containing methods and attributes relevant to ATM operations.
  • This approach is useful for simulating multiple ATMs in a banking application or testing functionalities independently.
python

Output

text

Accessing the 'cid' attribute of multiple objects in Python

Explanation

  • The code prints the 'cid' attribute from three different objects: c1, c2, and c3.
  • Each object is expected to be an instance of a class that has a 'cid' attribute defined.
  • This snippet is useful for debugging or displaying the unique identifiers of these objects.
  • The output will show the values of 'cid' for each object sequentially in the console.
python

Output

text

Accessing the counter attribute of an ATM class instance in Python

Explanation

  • The code snippet references the counter attribute of an instance of the Atm class.
  • This attribute likely tracks the number of transactions or interactions with the ATM.
  • The use of the dot notation indicates that counter is a property of the Atm object.
  • The value of Atm.counter can be used for monitoring or logging purposes in a banking application.
python

Output

text

This code assigns a string value to a class attribute of the Atm class.

Explanation

  • The code sets the class attribute counter of the Atm class to the string 'hehehe'.
  • This means that all instances of the Atm class will share this attribute value.
  • Class attributes are typically used for values that should be consistent across all instances.
  • The assignment does not create an instance of the class; it directly modifies the class itself.
  • This can be useful for tracking state or configuration that applies to all objects of the class.
python

This code initializes an instance of the Atm class in Python.

Explanation

  • The variable c4 is assigned a new object created from the Atm class.
  • This instance can now access all methods and properties defined within the Atm class.
  • The Atm class likely represents an automated teller machine, encapsulating related functionalities.
  • Further operations can be performed on c4 to simulate ATM transactions or behaviors.
python

Output

text

A Python ATM class that manages user accounts with balance and PIN functionalities

Explanation

  • Defines an Atm class with a static counter to assign unique customer IDs for each instance.
  • Implements a constructor that initializes the PIN and balance, and automatically increments the customer ID.
  • Provides methods to create and change a PIN, check the balance, and withdraw funds, ensuring PIN validation for secure transactions.
  • Uses private variables for balance management to encapsulate data and prevent direct access from outside the class.
  • Includes a menu-driven approach for user interaction, guiding users through various banking operations.
python

Creating multiple instances of an ATM class in Python

Explanation

  • This code snippet initializes three separate instances of the Atm class, named c1, c2, and c3.
  • Each instance represents an independent object, allowing for separate states and behaviors.
  • The Atm class must be defined elsewhere in the code, containing methods and attributes relevant to ATM operations.
  • This approach is useful for simulating multiple ATMs in a banking application or testing functionalities independently.
python

Output

text

Accessing the 'cid' attribute of multiple objects in Python

Explanation

  • The code prints the 'cid' attribute from three different objects: c1, c2, and c3.
  • Each object is expected to be an instance of a class that has a 'cid' attribute defined.
  • This snippet is useful for debugging or displaying the unique identifiers of these objects.
  • The output will show the values of 'cid' for each object sequentially in the console.
python

Output

text

Accessing a private variable in a Python class using name mangling

Explanation

  • The code snippet demonstrates how to access a private variable in a class by using name mangling, which alters the variable's name to include the class name.
  • The variable _Atm__counter is intended to be private, indicated by the underscore prefix, and is automatically transformed by Python to prevent direct access from outside the class.
  • This technique is useful for encapsulation, allowing the class to control access to its internal state while still providing a way to reference the variable if necessary.
  • Understanding name mangling is essential for developers working with object-oriented programming in Python, especially when dealing with inheritance and subclassing.
python

Output

text

Static Methods

A Python ATM Class Implementation for Managing User Accounts and Transactions

Explanation

  • Defines an Atm class that simulates an ATM system with functionalities like creating and changing a PIN, checking balance, and withdrawing money.
  • Utilizes a static variable __counter to uniquely identify each ATM instance.
  • Implements encapsulation by using private variables (e.g., __balance) to protect sensitive data from direct access.
  • Provides utility methods such as get_balance and set_balance for controlled access to the account balance.
  • Contains a private method __menu that presents a user interface for interacting with the ATM functionalities.
python

Instantiating an ATM object in Python for financial transactions

Explanation

  • The code creates an instance of the Atm class, which likely represents an Automated Teller Machine.
  • The variable c1 holds the reference to this newly created Atm object, allowing access to its methods and properties.
  • This instantiation is essential for performing operations such as withdrawals, deposits, or balance inquiries associated with the ATM functionality.
python

Output

text

Retrieving the current value of a counter from an object in Python

Explanation

  • The method get_counter() is called on the object c1, which is likely an instance of a class that maintains a counter.
  • This method is expected to return the current value of the counter, which could be an integer or another numeric type.
  • The implementation of get_counter() would typically involve accessing a private or protected attribute that stores the counter's value.
  • This functionality is useful for tracking counts or occurrences in various applications, such as event handling or resource management.
python

Output

text

This code retrieves the current counter value from an ATM object.

Explanation

  • The method get_counter() is called on an instance of the Atm class.
  • It likely returns the number of transactions or operations performed by the ATM.
  • This function can be useful for monitoring usage statistics or for debugging purposes.
  • The method may return an integer value representing the counter's current state.
python

Output

text

###Q1:Count number of instances of a class created in Python?

Example: Say Car is any class.

text

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.

This code implements a class to count the number of Car instances created.

Explanation

  • A class variable __counter is initialized to zero to keep track of the number of Car instances.
  • The constructor __init__ increments the __counter each time a new Car object is instantiated.
  • The method get_counter returns the current value of __counter, allowing access to the total number of Car instances.
  • Four instances of the Car class are created, which increments the counter to four.
  • Finally, the total count of Car instances is printed, displaying the value of __counter.
python

Output

text

###Q-2: Create a deck of cards class. Internally, the deck of cards should use another class, a card class. Your requirements are:

  • The Deck class 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 - suit and value
  • <suit> of <value> should dsiplay on printing any card object.

Creating and managing a standard playing card deck with shuffling and dealing functionality

Explanation

  • The code defines two classes, Card and Deck, to model a standard 52-card playing deck with suits and values
  • The Deck class initializes with all possible card combinations using list comprehension and includes methods to shuffle and deal cards
  • The shuffle method validates that the deck is full before shuffling and uses Python's random.shuffle() function to randomize card order
  • The deal method removes and returns the last card from the deck while handling the case when all cards have been dealt
  • The code demonstrates the complete workflow by creating a deck, shuffling it, dealing two cards, and displaying the remaining card count
python

Output

text

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.

Creating a Rectangle class to calculate area and check if it's a square

Explanation

  • Defines a Rectangle class with an initializer that sets the length and breadth of the rectangle.
  • Utilizes a class method property to create an instance of Rectangle using given dimensions.
  • Implements an area method that calculates the area by multiplying length and breadth.
  • Includes an is_square method that checks if the rectangle is a square by comparing its length and breadth.
  • Demonstrates usage by creating a rectangle instance and printing its area and square status.
python

Output

text

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.

This Python code manages product manufacturing and expiry dates while calculating the remaining time until expiration.

Explanation

  • The Product class initializes with user inputs for manufacturing and expiry dates, formatted as MM/DD/YYYY.
  • It converts the input strings into datetime objects for accurate date manipulation.
  • The time_to_expire method checks the current date against the expiry date to determine if the product is expired.
  • If the product is still valid, it calculates and prints the remaining days until expiration.
  • An instance of the Product class is created, and the time_to_expire method is called to display the result.
python

Output

text

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.

This Python code defines a Student class with encapsulated attributes and validation methods for age and marks.

Explanation

  • The Student class encapsulates student information such as student ID, marks, and age using private attributes.
  • Setter methods (set_sid, set_marks, set_age) allow controlled modification of the private attributes.
  • Getter methods (get_sid, get_marks, get_age) provide access to the private attributes while maintaining encapsulation.
  • The validate_age method checks if the student's age is greater than 20, while validate_marks ensures marks are within the range of 0 to 100.
  • The check_qualification method determines if the student qualifies based on age and marks, returning True if marks are 65 or higher and both validations pass.
python

Output

text

###Q-6: Ice-Cream Scoops and Bowl shop

  1. Create a class Scoop which has one public property flavor and one private proptery price. Take flavor values during object creation.

  2. Create a class Bowl with private prperty scoop_list which will have list of scoopd object.

  3. Create a method add_scoops in Bowl class which will add any no of Scoop objects given as parameter and store it in scoops_list.

  4. Make getter and setter method for price property.

  5. Make a method display to display flavour and price of each Scoop in scoop_list and print total price of the bowl by adding all flavour scoops prices.

  6. Make a method sold in both Scoop class and Bowl class to print no of quantity sold.

Ex.-

text

Output

text

This Python code defines classes for managing ice cream scoops and bowls, tracking their prices and quantities.

Explanation

  • The Scoop class represents an ice cream scoop with attributes for flavor and price, and maintains a static counter to track the number of scoops created.
  • The get_price and set_price methods allow for retrieving and setting the price of a scoop, while the __str__ method provides a string representation of the scoop's details.
  • The Bowl class manages a collection of Scoop objects, allowing for the addition of scoops and displaying their details along with the total price.
  • Both classes include a static method sold that returns the total number of instances created, providing insight into how many scoops or bowls have been sold.
  • The use of private attributes (e.g., __price, __scoop_list) ensures encapsulation, protecting the internal state of the objects from direct modification.
python

Managing Ice Cream Scoops and Their Pricing in a Bowl Class

Explanation

  • Creates instances of Scoop for different ice cream flavors and sets their prices.
  • Initializes a Bowl object to hold the scoops of ice cream.
  • Uses the add_scoops method to add one or multiple scoops to the bowl, demonstrating flexibility in input handling.
  • Calls the display method on the bowl to show the contents and possibly the total price.
  • Prints the total number of scoops sold and the total number of bowls sold, likely using class methods from Scoop and Bowl.
python

Output

text

###Q-7:Ice-Cream Bowl continue..

Making advancement in the above classes. Scoop and Bowl

  1. Introduce a property max_scoops in Bowl class to signify maximum scoops that a bowl can have, exceeding that it will display Bowl is full. Take default value as 3.

  2. no_of_scoop in Scoop class with default value of 1

  3. Print <flavour> added with every scoop added.

text

Output:

text

Testing code-2 considering above test code executed

text

Output

text

Testing code-3, considering above tests executed

text

Output:

text

This Python code defines classes for managing ice cream scoops and bowls with pricing and capacity features.

Explanation

  • The Scoop class represents an ice cream scoop with attributes for flavor, number of scoops, and price, while maintaining a class-level counter for the total number of scoops created.
  • The get_price and set_price methods allow for retrieving and setting the price of a scoop, respectively.
  • The __str__ method provides a string representation of the scoop, displaying its flavor and price.
  • The Bowl class manages a collection of Scoop objects, enforcing a maximum scoop limit and tracking the total number of bowls created.
  • The add_scoops method adds new scoops to the bowl if the total does not exceed the maximum capacity, while the display method prints each scoop's details and calculates the total price.
python

Creating and managing ice cream scoops and bowls with customizable attributes in Python

Explanation

  • The code defines instances of a Scoop class for different ice cream flavors, allowing customization of scoop count and price.
  • Each scoop is created with a specific flavor and an optional number of scoops; if not provided, a default value is used.
  • A Bowl class instance is created to hold multiple scoops, with the ability to add one or more scoops at a time.
  • The display method of the Bowl class is called to show the contents and details of the scoops added to the bowl.
python

Output

text

Next in this series: Python Inheritance & Polymorphism: OOP Patterns & Examples →

Frequently Asked Questions

The Point class represents 2D coordinates with methods to calculate Euclidean distance between points and distance from origin using the Pythagorean theorem.
The Line class uses the linear equation Ax + By + C = 0 to determine if a point lies on the line by checking if the equation evaluates to zero with the point's coordinates.
The euclideandistance method implements the distance formula derived from the Pythagorean theorem for calculating straight-line distances between two coordinate points.
The shortestdistance method uses the standard formula for point-to-line distance in coordinate geometry, involving absolute value and square root calculations.
A Line object is initialized with parameters A, B, and C, which likely represent slope and intercept values in the linear equation Ax + By + C = 0.

How was this tutorial?