Skip to main content

In Python Class how to create an instance variable, so each instance will have it's own copy of the values

Python: 1) Instance Variable 2) Class Variable

Creating Instance Variables:

In Python, to create an instance variable (i.e., a variable that is specific to each instance of a class), you define the variable inside the __init__ method. This ensures that each instance of the class will have its own copy of the variable.

Here’s an example:

class MyClass:
    def __init__(self, value):
        # This is an instance variable. Each instance gets its own copy.
        self.instance_variable = value

# Creating instances
obj1 = MyClass(10)
obj2 = MyClass(20)

# Accessing instance variables
print(obj1.instance_variable)  # Output: 10
print(obj2.instance_variable)  # Output: 20

Key Points:

  1. self: Refers to the instance of the class. You use self to define variables that should be unique to each instance.
  2. Instance variables are defined inside the __init__ method. This ensures that every time an object is created, it has its own independent variable.
  3. obj1.instance_variable and obj2.instance_variable are independent because they are tied to different instances (obj1 and obj2).

Each object created from the class gets its own instance of instance_variable, and changes to one object’s variable won't affect the others.

In Python, if you want to create variables that are not instance variables but are still part of the class, you can use class variables. These variables are shared across all instances of the class.

Creating Class Variables:

Class variables are defined outside of the __init__ method but inside the class body. They are shared by all instances of the class.

Here’s an example:

class MyClass:
    # This is a class variable
    class_variable = 0
    
    def __init__(self, value):
        # This is an instance variable
        self.instance_variable = value

# Creating instances
obj1 = MyClass(10)
obj2 = MyClass(20)

# Accessing class variable through the class itself
print(MyClass.class_variable)  # Output: 0

# Accessing class variable through an instance
print(obj1.class_variable)  # Output: 0
print(obj2.class_variable)  # Output: 0

# Changing class variable
MyClass.class_variable = 100
print(obj1.class_variable)  # Output: 100
print(obj2.class_variable)  # Output: 100

Key Points:

  1. Class variables are defined directly within the class, outside of any methods (including __init__).
  2. They are shared across all instances of the class. If you change the value of a class variable, it changes for all instances.
  3. Class variables can be accessed either by the class name (MyClass.class_variable) or through an instance (obj1.class_variable), but they are the same for all instances unless you specifically modify them at the instance level.

Example of Changing a Class Variable at the Instance Level:

# Creating an instance
obj1 = MyClass(10)

# Changing the class variable at the instance level
obj1.class_variable = 200

# Accessing class variable through the instance after change
print(obj1.class_variable)  # Output: 200

# Accessing class variable through the class name
print(MyClass.class_variable)  # Output: 100 (not affected by the instance-level change)

In this case, obj1.class_variable = 200 doesn't affect the class-level variable but creates an instance-specific variable for obj1 that shadows the class variable.

Comments

Popular posts from this blog

Simple Linear Regression - and Related Regression Loss Functions

Today's Topics: a. Regression Algorithms  b. Outliers - Explained in Simple Terms c. Common Regression Metrics Explained d. Overfitting and Underfitting e. How are Linear and Non Linear Regression Algorithms used in Neural Networks [Future study topics] Regression Algorithms Regression algorithms are a category of machine learning methods used to predict a continuous numerical value. Linear regression is a simple, powerful, and interpretable algorithm for this type of problem. Quick Example: These are the scores of students vs. the hours they spent studying. Looking at this dataset of student scores and their corresponding study hours, can we determine what score someone might achieve after studying for a random number of hours? Example: From the graph, we can estimate that 4 hours of daily study would result in a score near 80. It is a simple example, but for more complex tasks the underlying concept will be similar. If you understand this graph, you will understand this blog. Sim...

What problems can AI Neural Networks solve

How does AI Neural Networks solve Problems? What problems can AI Neural Networks solve? Based on effectiveness and common usage, here's the ranking from best to least suitable for neural networks (Classification Problems, Regression Problems and Optimization Problems.) But first some Math, background and related topics as how the Neural Network Learn by training (Supervised Learning and Unsupervised Learning.)  Background Note - Mathematical Precision vs. Practical AI Solutions. Math can solve all these problems with very accurate results. While Math can theoretically solve classification, regression, and optimization problems with perfect accuracy, such calculations often require impractical amounts of time—hours, days, or even years for complex real-world scenarios. In practice, we rarely need absolute precision; instead, we need actionable results quickly enough to make timely decisions. Neural networks excel at this trade-off, providing "good enough" solutions in seco...

Activation Functions in Neural Networks

  A Guide to Activation Functions in Neural Networks 🧠 Question: Without activation function can a neural network with many layers be non-linear? Answer: Provided at the end of this document. Activation functions are a crucial component of neural networks. Their primary purpose is to introduce non-linearity , which allows the network to learn the complex, winding patterns found in real-world data. Without them, a neural network, no matter how deep, would just be a simple linear model. In the diagram below the f is the activation function that receives input and send output to next layers. Commonly used activation functions. 1. Sigmoid Function 2. Tanh (Hyperbolic Tangent) 3. ReLU (Rectified Linear Unit - Like an Electronic Diode) 4. Leaky ReLU & PReLU 5. ELU (Exponential Linear Unit) 6. Softmax 7. GELU, Swish, and SiLU 1. Sigmoid Function                       The classic "S-curve," Sigmoid squashes any input value t...