how to dynamically access/overwrite a field in a class using a variable?

  • Last Update :
  • Techknowledgy :

Thanks to @kindall's and @skullgoblet1089's responses I was able to figure this out, but for anyone else that has this problem, let me show you the working code:

for key in my_class_instance_1.__dict__.keys():
   if key != "key_i_dont_want_to_overwrite":
   val = getattr(my_class_instance_2, key) # the new value
setattr(my_class_instance_1, key, val) # overwriting the old value

Suggestion : 2

11/08/2021

At the top of the ReadOnlyFile.cs or ReadOnlyFile.vb file, add the following code to import the System.IO and System.Dynamic namespaces.

using System.IO;
using System.Dynamic;
using System.IO;
using System.Dynamic;
Imports System.IO
Imports System.Dynamic

The custom dynamic object uses an enum to determine the search criteria. Before the class statement, add the following enum definition.

public enum StringSearchOption {
   StartsWith,
   Contains,
   EndsWith
}
public enum StringSearchOption
{
    StartsWith,
    Contains,
    EndsWith
}
Public Enum StringSearchOption
StartsWith
Contains
EndsWith
End Enum

Update the class statement to inherit the DynamicObject class, as shown in the following code example.

class ReadOnlyFile: DynamicObject
class ReadOnlyFile : DynamicObject
Public Class ReadOnlyFile
Inherits DynamicObject

Add the following code to the ReadOnlyFile class to define a private field for the file path and a constructor for the ReadOnlyFile class.

// Store the path to the file and the initial line count value.
private string p_filePath;

// Public constructor. Verify that file exists and store the path in
// the private variable.
public ReadOnlyFile(string filePath) {
   if (!File.Exists(filePath)) {
      throw new Exception("File path does not exist.");
   }

   p_filePath = filePath;
}
' Store the path to the file and the initial line count value.
Private p_filePath As String

   ' Public constructor. Verify that file exists and store the path in 
' the private variable.
Public Sub New(ByVal filePath As String)
If Not File.Exists(filePath) Then
Throw New Exception("File path does not exist.")
End If

p_filePath = filePath
End Sub

Add the following GetPropertyValue method to the ReadOnlyFile class. The GetPropertyValue method takes, as input, search criteria and returns the lines from a text file that match that search criteria. The dynamic methods provided by the ReadOnlyFile class call the GetPropertyValue method to retrieve their respective results.

public List<string> GetPropertyValue(string propertyName,
                                     StringSearchOption StringSearchOption = StringSearchOption.StartsWith,
                                     bool trimSpaces = true)
{
    StreamReader sr = null;
    List<string> results = new List<string>();
    string line = "";
    string testLine = "";

    try
    {
        sr = new StreamReader(p_filePath);

        while (!sr.EndOfStream)
        {
            line = sr.ReadLine();

            // Perform a case-insensitive search by using the specified search options.
            testLine = line.ToUpper();
            if (trimSpaces) { testLine = testLine.Trim(); }

            switch (StringSearchOption)
            {
                case StringSearchOption.StartsWith:
                    if (testLine.StartsWith(propertyName.ToUpper())) { results.Add(line); }
                    break;
                case StringSearchOption.Contains:
                    if (testLine.Contains(propertyName.ToUpper())) { results.Add(line); }
                    break;
                case StringSearchOption.EndsWith:
                    if (testLine.EndsWith(propertyName.ToUpper())) { results.Add(line); }
                    break;
            }
        }
    }
    catch
    {
        // Trap any exception that occurs in reading the file and return null.
        results = null;
    }
    finally
    {
        if (sr != null) {sr.Close();}
    }

    return results;
}
Public Function GetPropertyValue(ByVal propertyName As String,
   Optional ByVal StringSearchOption As StringSearchOption = StringSearchOption.StartsWith,
   Optional ByVal trimSpaces As Boolean = True) As List(Of String)

Dim sr As StreamReader = Nothing
Dim results As New List(Of String)
Dim line = ""
Dim testLine = ""

Try
sr = New StreamReader(p_filePath)

While Not sr.EndOfStream
line = sr.ReadLine()

' Perform a case-insensitive search by using the specified search options.
testLine = UCase(line)
If trimSpaces Then testLine = Trim(testLine)

Select Case StringSearchOption
Case StringSearchOption.StartsWith
If testLine.StartsWith(UCase(propertyName)) Then results.Add(line)
Case StringSearchOption.Contains
If testLine.Contains(UCase(propertyName)) Then results.Add(line)
Case StringSearchOption.EndsWith
If testLine.EndsWith(UCase(propertyName)) Then results.Add(line)
End Select
End While
Catch
   ' Trap any exception that occurs in reading the file and return Nothing.
results = Nothing
Finally
If sr IsNot Nothing Then sr.Close()
End Try

Return results
End Function

After the GetPropertyValue method, add the following code to override the TryGetMember method of the DynamicObject class. The TryGetMember method is called when a member of a dynamic class is requested and no arguments are specified. The binder argument contains information about the referenced member, and the result argument references the result returned for the specified member. The TryGetMember method returns a Boolean value that returns true if the requested member exists; otherwise it returns false.

// Implement the TryGetMember method of the DynamicObject class for dynamic member calls.
public override bool TryGetMember(GetMemberBinder binder,
   out object result) {
   result = GetPropertyValue(binder.Name);
   return result == null ? false : true;
}
' Implement the TryGetMember method of the DynamicObject class for dynamic member calls.
Public Overrides Function TryGetMember(ByVal binder As GetMemberBinder,
   ByRef result As Object) As Boolean
result = GetPropertyValue(binder.Name)
Return If(result Is Nothing, False, True)
End Function

Suggestion : 3

Here are some guidelines for writing consistent, usable APIs for libraries.,Naming is an important part of writing readable, maintainable code. The following best practices can help you achieve that goal.,Local variables, especially in modern code where functions tend to be small, have very little scope. Omitting the type focuses the reader’s attention on the more important name of the variable and its initialized value.,It’s particularly important to be consistent here because these parameters are usually unnamed. If your API takes a length instead of an end point, the difference won’t be visible at all at the call site.

E for the element type in a collection:

class IterableBase<E> {}
class List<E> {}
class HashSet<E> {}
class RedBlackTree<E> {}

K and V for the key and value types in an associative collection:

class Map<K, V> {}
class Multimap<K, V> {}
class MapEntry<K, V> {}

R for a type used as the return type of a function or a class’s methods. This isn’t common, but appears in typedefs sometimes and in classes that implement the visitor pattern:

abstract class ExpressionVisitor<R> {
  R visitBinary(BinaryExpression node);
  R visitLiteral(LiteralExpression node);
  R visitUnary(UnaryExpression node);
}

Otherwise, use T, S, and U for generics that have a single type parameter and where the surrounding type makes its meaning obvious. There are multiple letters here to allow nesting without shadowing a surrounding name. For example:

class Future<T> {
  Future<S> then<S>(FutureOr<S> onValue(T value)) => ...
}

This does not mean the operation has to be particularly fast in order to be a getter. IterableBase.length is O(n), and that’s OK. It’s fine for a getter to do significant calculation. But if it does a surprising amount of work, you may want to draw their attention to that by making it a method whose name is a verb describing what it does.

connection.nextIncomingMessage; // Does network I/O.
expression.normalForm; // Could be exponential to calculate.

The “user-visible” part is important. It’s fine for getters to modify hidden state or produce out of band side effects. Getters can lazily calculate and store their result, write to a cache, log stuff, etc. As long as the caller doesn’t care about the side effect, it’s probably fine.

stdout.newline; // Produces output.
list.clear; // Modifies object.

Suggestion : 4

Used only for single-row queries, the INTO clause specifies the variables or record into which column values are retrieved. For each value retrieved by the query, there must be a corresponding, type-compatible variable or field in the INTO clause.,Used only for DML statements that have a RETURNING clause (without a BULK COLLECT clause), the RETURNING INTO clause specifies the variables into which column values are returned. For each value returned by the DML statement, there must be a corresponding, type-compatible variable in the RETURNING INTO clause.,Use concatenation to build the string, rather than trying to pass the table name as a bind variable through the USING clause.,the fact that the name X is repeated is not significant. You can code the corresponding USING clause with four different bind variables:

Example 7-1 Examples of Dynamic SQL

CREATE OR REPLACE PROCEDURE raise_emp_salary(column_value NUMBER,
   emp_column VARCHAR2, amount NUMBER) IS
v_column VARCHAR2(30);
sql_stmt VARCHAR2(200);
BEGIN
--determine
if a valid column name has been given as input
SELECT COLUMN_NAME INTO v_column FROM USER_TAB_COLS
WHERE TABLE_NAME = 'EMPLOYEES'
AND COLUMN_NAME = emp_column;
sql_stmt: = 'UPDATE employees SET salary = salary + :1 WHERE ' ||
   v_column || ' = :2';
EXECUTE IMMEDIATE sql_stmt USING amount, column_value;
IF SQL % ROWCOUNT > 0 THEN
DBMS_OUTPUT.PUT_LINE('Salaries have been updated for: ' || emp_column ||
   ' = ' || column_value);
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Invalid Column: ' || emp_column);
END raise_emp_salary;
/

DECLARE
plsql_block VARCHAR2(500);
BEGIN
--note the semi - colons(;) inside the quotes '...'
plsql_block: = 'BEGIN raise_emp_salary(:cvalue, :cname, :amt); END;';
EXECUTE IMMEDIATE plsql_block USING 110, 'DEPARTMENT_ID', 10;
EXECUTE IMMEDIATE 'BEGIN raise_emp_salary(:cvalue, :cname, :amt); END;'
USING 112, 'EMPLOYEE_ID', 10;
END;
/

DECLARE
sql_stmt VARCHAR2(200);
v_column VARCHAR2(30): = 'DEPARTMENT_ID';
dept_id NUMBER(4): = 46;
dept_name VARCHAR2(30): = 'Special Projects';
mgr_id NUMBER(6): = 200;
loc_id NUMBER(4): = 1700;
BEGIN
--note that there is no semi - colon(;) inside the quotes '...'
EXECUTE IMMEDIATE 'CREATE TABLE bonus (id NUMBER, amt NUMBER)';
sql_stmt: = 'INSERT INTO departments VALUES (:1, :2, :3, :4)';
EXECUTE IMMEDIATE sql_stmt USING dept_id, dept_name, mgr_id, loc_id;
EXECUTE IMMEDIATE 'DELETE FROM departments WHERE ' || v_column || ' = :num'
USING dept_id;
EXECUTE IMMEDIATE 'ALTER SESSION SET SQL_TRACE TRUE';
EXECUTE IMMEDIATE 'DROP TABLE bonus';
END;
/

Example 7-2 Dynamic SQL Procedure that Accepts Table Name and WHERE Clause

CREATE TABLE employees_temp AS SELECT * FROM employees;

CREATE OR REPLACE PROCEDURE delete_rows(
   table_name IN VARCHAR2,
   condition IN VARCHAR2 DEFAULT NULL) AS
where_clause VARCHAR2(100): = ' WHERE ' || condition;
v_table VARCHAR2(30);
BEGIN
--first make sure that the table actually exists;
if not, raise an exception
SELECT OBJECT_NAME INTO v_table FROM USER_OBJECTS
WHERE OBJECT_NAME = UPPER(table_name) AND OBJECT_TYPE = 'TABLE';
IF condition IS NULL THEN where_clause: = NULL;
END IF;
EXECUTE IMMEDIATE 'DELETE FROM ' || v_table || where_clause;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Invalid table: ' || table_name);
END;
/
BEGIN
delete_rows('employees_temp', 'employee_id = 111');
END;
/

You must specify the parameter mode in more complicated cases, such as this one where you call a procedure from a dynamic PL/SQL block:

CREATE PROCEDURE create_dept(
   deptid IN OUT NUMBER,
   dname IN VARCHAR2,
   mgrid IN NUMBER,
   locid IN NUMBER) AS
BEGIN
SELECT departments_seq.NEXTVAL INTO deptid FROM dual;
INSERT INTO departments VALUES(deptid, dname, mgrid, locid);
END;
/

Example 7-3 Using IN OUT Bind Arguments to Specify Substitutions

DECLARE
plsql_block VARCHAR2(500);
new_deptid NUMBER(4);
new_dname VARCHAR2(30): = 'Advertising';
new_mgrid NUMBER(6): = 200;
new_locid NUMBER(4): = 1700;
BEGIN
plsql_block: = 'BEGIN create_dept(:a, :b, :c, :d); END;';
EXECUTE IMMEDIATE plsql_block
USING IN OUT new_deptid, new_dname, new_mgrid, new_locid;
END;
/

Example 7-3 Using IN OUT Bind Arguments to Specify Substitutions

DECLARE
plsql_block VARCHAR2(500);
new_deptid NUMBER(4);
new_dname VARCHAR2(30): = 'Advertising';
new_mgrid NUMBER(6): = 200;
new_locid NUMBER(4): = 1700;
BEGIN
plsql_block: = 'BEGIN create_dept(:a, :b, :c, :d); END;';
EXECUTE IMMEDIATE plsql_block
USING IN OUT new_deptid, new_dname, new_mgrid, new_locid;
END;
/

Example 7-4 Dynamic SQL with BULK COLLECT INTO Clause

DECLARE
TYPE EmpCurTyp IS REF CURSOR;
TYPE NumList IS TABLE OF NUMBER;
TYPE NameList IS TABLE OF VARCHAR2(25);
emp_cv EmpCurTyp;
empids NumList;
enames NameList;
sals NumList;
BEGIN
OPEN emp_cv FOR 'SELECT employee_id, last_name FROM employees';
FETCH emp_cv BULK COLLECT INTO empids, enames;
CLOSE emp_cv;
EXECUTE IMMEDIATE 'SELECT salary FROM employees'
BULK COLLECT INTO sals;
END;
/

Example 7-5 Dynamic SQL with RETURNING BULK COLLECT INTO Clause

DECLARE
TYPE NameList IS TABLE OF VARCHAR2(15);
enames NameList;
bonus_amt NUMBER: = 50;
sql_stmt VARCHAR(200);
BEGIN
sql_stmt: = 'UPDATE employees SET salary = salary + :1 
RETURNING last_name INTO: 2 ';
EXECUTE IMMEDIATE sql_stmt
USING bonus_amt RETURNING BULK COLLECT INTO enames;
END;
/

Suggestion : 5

You can see that both the properties inside :root and the media query get lost after compilation, because SASS variables cannot exist inside a CSS file (or, to be more precise, they can be forced to exist in a CSS file, but are ignored since some of their syntax is invalid CSS), so the variable’s value can not be updated afterwards.,Now let’s consider the same case, but applied using only CSS Variables with no CSS pre/postprocessor applied (i.e., without any no transpilation or compilation being performed):,The syntax for CSS custom properties is a bit weird compared to other languages, but it makes a whole lot of sense if you compare their syntax with other features in the same CSS ecosystem:,Theming: Using a set of themes for a site is rather easy when implementing CSS variables. Want a light or dark variation of your current style? Just change the value of some custom properties using JavaScript and you’re done.

Let’s take a look at an example:

.element {
   color: blue;
   border: 2 px solid currentColor; /* Sets a solid, 2px wide, blue border to the element */
}

In addition to cascading, this can also produce the following:

.element span {
   background: currentColor; /* Sets a blue background color for every span child of .element, unless a color property is declared in this same block */
}

.element span.red {
   color: red; /* Sets a red background color for every span child of .element that has the class .red, since currentColor is applied to the background of every span child of .element no matter if they have the .red class or not */
}

The syntax for CSS custom properties is a bit weird compared to other languages, but it makes a whole lot of sense if you compare their syntax with other features in the same CSS ecosystem:

: root {
   --color - black: #2e2e2e;
}

.element {
  background: var(--color-black);
}

This snippet of SASS declarations and rules compiles to CSS as follows:

.corners {
   border - radius: 30 px;
}

Now let’s consider the same case, but applied using only CSS Variables with no CSS pre/postprocessor applied (i.e., without any no transpilation or compilation being performed):

: root {
   --value: 30 px;
}

@media screen and(min - width: 768 px) {
      --value: 60 px;
   }

   .corners {
      border - radius: var (--value);
   }

Suggestion : 6

Last modified: Aug 1, 2022, by MDN contributors

git clone https: //github.com/opensas/mdn-svelte-tutorial.git
cd mdn - svelte - tutorial / 03 - adding - dynamic - behavior
npx degit opensas / mdn - svelte - tutorial / 03 - adding - dynamic - behavior
<script>
  let todos = [
    { id: 1, name: 'Create a Svelte starter app', completed: true },
    { id: 2, name: 'Create your first component', completed: true },
    { id: 3, name: 'Complete the rest of the tutorial', completed: false }
  ]
  let totalTodos = todos.length
  let completedTodos = todos.filter((todo) => todo.completed).length
</script>
<h2 id="list-heading">{completedTodos} out of {totalTodos} items completed</h2>
<ul>
{#each todos as todo, index (todo.id)}
  <li>
    <input type="checkbox" checked={todo.completed}/> {index}. {todo.name} (id: {todo.id})
  </li>
{:else}
  Nothing to do here!
{/each}
</ul>

Suggestion : 7

Classes in Java exist in a hierarchy. A class in Java can be declared as a subclass of another class using the extends keyword. A subclass inherits variables and methods from its superclass and can use them as if they were declared within the subclass itself:,A subclass can be further subclassed. Normally, subclassing specializes or refines a class by adding variables and methods (you cannot remove or hide variables or methods by subclassing). For example:,If the first statement of a constructor is a call to a superclass constructor via super(), Java invokes the selected superclass constructor. Upon its return, Java initializes the current class’s instance variables and proceeds with the statements of the current constructor.,Instance variables of the class are initialized upon return from the superclass constructor, whether that’s due to an explicit call to super() or an implicit call to the default superclass constructor.

    class IntegerCalculator {
       int sum;
       ...
    }

    class DecimalCalculator extends IntegerCalculator {
       double sum;
       ...
    }
    Cat simon = new Cat();
    Animal creature = simon;
    ...
    creature.sleep(); // accesses Cat sleep();
    class Cat extends Mammal {
       ...
       @Override void sleep() {
          ...
       }
    }
    static final boolean DEBUG = false;
    ...
    final void debug(String message) {
       if (DEBUG) {
          System.err.println(message);
          // do other stuff
          ...
       }
    }
    public void readFile() throws IOException {
       ...
       if (error) throw new FileNotFoundException(filename);
    }
    class Animal {
       Animal create() {
          ...
       }
    }
    class Mammal extends Animal {
       Mammal create() {
          ...
       }
    }