How to initialize object attributes from an array of strings in Python? - python-3.x

I am supposed to write a class which will allow the user of the script to define what attributes will it's objects have when initializing them by giving it an array of strings like this.
data = Database(tables=['distance', 'speed'])
Then it should be possible to call the class's methods like
data.distance.insert({1: 25, 2: 55})
data.speed.mean()
etc.
I have tried using setattr() this way
data = Database()
tables=['distance', 'speed']
for item in tables:
setattr(data, item, item)
which works, but isn't exactly what it should be.
Any ideas how to do it directly inside the class?

Related

If I return a class instance inside a class function, it creates a new object or it returns the existing object associated to that data?

For example:
class DogOwners(object): def get_this_animal(id, dog_name): return Dog(id=id, name=dog_name)
Would this return a new object or the existing one associated to the *args of get_this_animal()?
It returns the data I want but I can't tell if now I have two dogs with the same data
Any time you run Dog(...), you're creating a new object (assuming you didn't do anything special to the class to change that fact). Calling a class as a function constructs a new instance by default. You can also check this yourself using id:
# I added the necessary 'self' parameter, and changed the 'id' parameter
def get_this_animal(self, dog_id, dog_name):
new_dog = Dog(id=dog_id, name=dog_name)
print(id(self), id(new_dog)) # These will not be the same
return new_dog
That print will print two sepeate addresses/IDs, indicating that they're distinct objects. The dog_id and dog_name objects will be the same, however.
It would return a new dog with those attributes assuming that Dog(id=id, name =dog_name) is your constructor. The program doesn't have a way to instead return existing dogs with the same attributes as you've written it. If you wanted to not create a new dog then you'd need to store the data of all the dogs and search for that specific data to ensure you return the same dog. This storage and search can be done through several ways like a dictionary, array/list, and so on (likely a dictionary is better for what you're trying to do).

Understanding Object Orientation Multiple Periods

I have a Object Oritentation quesation.
I have created the following Pandas series:-
import pandas as pd
my_series1 = pd.Series(data = [200,201,202,203], index = ["London", "New York", "London", "Sydney"], name = "Test")
my_series1 is an object from the Class series (I think)
my_series1 has access to methods and properties, one example of this is checking if all the values in the series are unique using the code:-
my_series1.is_unique
I am happy with the above code.
This is where things get confusing, I can check if the index values are also unique using the code:-
mmy_series1.index.is_unique
The code above does not make sense to me, I don't fully understand how the is_unique property can be applied to the index column - I have been assuming that once an object has been created you can access a method by calling the object name followed by a "." and then the name of the function.
This idea of multiple periods is confusing me as i cannot connect the is_unique back to how the class is created.
Also would it be correct to say the following:-
An object has attributes
An object has methods
But are properties of an object??, are object properties and methods the same thing?
Can anyone help?
Thank you.

Remove Member for rapid JSON nested objects

Are there examples to remove a member within a nested JSON object?
For example: Consider the below JSON snippet, how would I be able to remove member C from the rapid son library?
{
"a": 1,
"b":{"c" : 2, "d" : 3}
}
I am not looking for hardcoded removal.. Like a.RemoveMember("c"); I am looking for code examples to remove a member from a rapid JSON document using the member iterator.
All the examples I see are for ConstMemberIterator. But RemoveMember can only be called with Member Iterators
From the document https://rapidjson.org/md_doc_tutorial.html, I am looking for an examples code snippet for the following function:
MemberIterator RemoveMember(MemberIterator): Remove a member by iterator (constant time complexity).
MemberIterator EraseMember(MemberIterator): similar to the above but it preserves order of members (linear time complexity).
MemberIterator EraseMember(MemberIterator first, MemberIterator last): remove a range of members, preserves order (linear time complexity).
I don't know if this can resolve your issue or not
(http://rapidjson.org/md_doc_pointer.html)
// Erase a member or element, return true if the value exists
bool success = Pointer("/b/c").Erase(d);
assert(success);
Edited
Yes, but it will erase the entire b object. The result will be {"a": 1}

How to avoid duplication of class instances in Python?

What is a good way to avoid duplication of a class instance when it is created using the __init__() function.
This question is a result of this issue.
Context (using employee class example):
Lets say I have an employee class: __init__(self,name,dept)
I also have a method, employee.info(self) that prints out name and dept of any employee.
However a user could just add an employee by calling a=employee(args..). They could do it multiple times using the same instance variable a, but different employee names.
This will cause issues if they try to print a.info(), as each time a different employee name will be printed.
Is there a better way to do this? I know it is possible to have the __init__() "pass" and define a new method to create an instance.
Expect results:
>>Adam=employee('marketing')
>>Adam.info()
>>Adam works in marketing.
OR
>>a=employee('Adam','marketing')
>>a=employee('Mary','marketing')
>>Error: employee instance with identifier "a" already exists.
>>Use employee.update() method to modify existing record.
Is there a cleaner way of doing it? (as you might guess, I am still learning python).
Or is it good practice to write an explicit function (instead of a class method) to add new employees?
what you try is impossible, because in
a=employee('Adam','marketing')
a is not an object but a variable that points to the object employee('Adam','marketing').
When you do
a=employee('Mary','marketing')
you say to python that now, a must now not point to the object employee('Adam','marketing') but to the object employee('Mary','marketing'). And then, if you have no more variable to reference the object employee('Adam','marketing'), the garbage collector will destroy it.
You must consider that in python all is object, but not the variables that are only references to manipulate objects.
I have been racking my brains over the same problem and have finally managed to figure out a workaround :
Create a dictionary that stores the employee name and the related object like this :
total_emp_dict = {}
Add this inside the def __init__ of the class employee : total_emp_dict[name] = self. This will ensure to add each employee name as key and the object associated will be added as value.
Now create a new function outside & before the employee class is defined, let's call it create_new_emp. It will go like this :
#function to check and avoid duplicate assignment of instances
def create_new_emp(name, dept):
if name in total_emp_dict:
return total_emp_dict[name]
else:
return employee(name, dept)
When creating a any new employee, use this new function : a = create_new_emp("Adam", HR) instead of a = employee("Adam", HR)
Explanation : This function will ensure that duplicate assignment is not done. If "a" is already assigned to "Adam", this function will return object of "Adam" to "a", when called again. But if nothing is assigned to "a", then this function will handover to the attributes (name, dept) to employee class and create a new instance. This instance will then be assigned to "a".
I don't know if this is the best solution for this problem, but honestly this is the only solution I have found so far and it works great for me without much fuss / extra code space. Hope it works for you too! :)

How to add individual elements of an object in an Arraylist through a for loop?

I am trying to add all elements of an object into ArrayList. elements of the object are of different type.
e.g. object Employee having attributes like emp_id,name,address,DOB.
I want to store each attribute as an object in an ArrayList. Like,
ArrayList[1] = Employee.emp_id
ArrayList[2] = Employee.name
ArrayList[3] = Employee.address
I want to do it dynamically. Like, in future more attributes are added in this object, without doing a manual work. Is there a way to create an array List?
ArrayList must be of the same type. You can have an ArrayList of type in which you can do what you are doing, since all objects in Java extend Object. If you are trying to store different Object types in an arraylist, however, this is not possible.
You may know that first part, just was a little unclear in your post.
Here's how to do it with objects using reflection:
//make sure you import java.lang.reflect.*
public void addMyFields(Employee e){
ArrayList<Object> list = new ArrayList();
for (Field field : emp.getClass().getDeclaredFields())
{
field.setAccessible(true);
list.add(field.get(emp);
}
}

Resources