I don't have much experience with python and probably this is duplicated question.. sorry for that
Let assume I have the following code:
class myclassI:
def __init__(self, key=None, data=None):
self.key = key
self.data= data
class myclassII:
def addInfo(self, key, data)
NewInfo = myclassI(key=key, data=data)
I see this type of call and I was wondering what do we mean by performing "key=key" when we are calling "myclassI"?
Many thanks for any suggestions!
Related
I have a function in a class (TableManager) that get the item and a specific field ('body') in DynamoDB.
class TableManager:
def get_body_dynamo(self, item):
get_body = json.loads(item.get('txt_vlr_parm_requ').get('body')) ##dict
return get_body
I need to initialize this 'body' field in another class (S3Connection), but I'm having trouble calling this function inside init.
class S3Connection:
def __init__(self, file, logs):
self.file = file
self.logs = logs
self.versions = None
I need something like this, to use this body I got from Dynamodb and create functions.
class S3Connection:
def __init__(self, file, logs, body_dynamo: TableManager.get_body_dynamo()):
self.body_dynamo = body_dynamo
self.file = file
self.logs = logs
self.versions = None
This way, of course, is giving error (not recognizing what body_dynamo is).
I'm new in programming and Python, so I appreciate any help.
I am trying to avoid the linter warning that is shown as a comment in the last line of the code sample.
I understand why it happens, and I know I could very well ignore because this is Python. But as a sort of self-exercise, I've been trying to think of a properly typed way to avoid it, and haven't been able to find a solution.
Here's a code sample:
class Content(ABC):
def __init__(self, data: Dict):
self._data: Dict = data
class AlertContent(Content):
def __init__(self, alert: Alert):
data: Dict = get_data_from_alert(alert)
super().__init__(data)
self.alert_priority: str = alert.priority
class Envelope(ABC):
def __init__(self, content: Content):
self._content: Content = content
#property
#abstractmethod
def priority(self) -> str:
raise NotImplementedError
class AlertEnvelope(Envelope):
def __init__(self, content: AlertContent):
super().__init__(content)
#property
#abstractmethod
def priority(self) -> str:
return self._content.alert_priority # Warning: Unresolved attribute reference 'alert_priority' for class 'Content'
Do you have any ideas?
I think this gets into a matter of style, but it's arguable that since having accurate typing is part of your design, that you don't actually want super().__init__(content) because you're constructing a class that relies on the concrete interface of AlertContent, while the parent class explicitly types the attribute with the more abstract type that does not implement the interface.
Thus,
class AlertEnvelope(Envelope):
def __init__(self, content: AlertContent):
self._content: AlertContent = content
might still be DRY code, considering what your goal is.
I ended up going for the following solution:
class AlertEnvelope(Envelope):
def __init__(self, content: AlertContent):
super().__init__(content)
# Inherited from Envelope
# #property
# def content(self) -> Content:
# return self._content
def alert_content(self) -> AlertContent:
return cast(AlertContent, self._content) # ** Reasoning below
#property
#abstractmethod
def priority(self) -> str:
return self.alert_content.alert_priority
** The reasons for the solution I chose are:
Even though cast doesn't do literally anything (defined as pass), it's a way for linters to know that something has changed in the typing, so you don't get an error. And, being pass, its cost is almost negligible.
Explicitness for anyone that reads the code that something's going on.
Mimics the way you'd do it in C++, a hard typed language, which kinda was one of my goals, to follow a hard typing approach.
I have a class that makes objects allowing me to access properties of an experimental camera system. I have some configuration properties saved in a dict for where certain cameras should be initially located. As these initial settings may vary I cannot hard code them into the class but need them separate in a text file that I access using the json library.
Is there a way to pass the dict into a class so its key value pairs can be used?
Simplified code
import any_dict_01
import json
data = any_dict_01
class dummy(data):
def __init__(self):
self.data = data
def getDict(self):
print(self.data)
a = dummy()
a.getDict()
Working Code
based on hints and advice from karl in the comments under the question I figured out how to do it (I hope karl puts his comments as an answer so I can accept it).
import json
data = 'my_rig.txt'
class dummy:
def __init__(self, data):
self.data = data
def getDict(self):
with open(data) as json_file:
data = json.load(json_file)
print(data)
a =dummy()
theDict = a.getDict(data)
By request:
data = any_dict_01 does not make data be any particular dict defined by the any_dict_01 module. It makes data be another name for that same module.
Anyway, this question isn't really about classes. The way you get information into the __init__ method is the same way that you get information into any ordinary function: by giving it a parameter, and passing the information in as an argument.
Your code would work by fixing the last part like this:
def __init__(self, data):
self.data = data
def getDict(self):
return self.data
a = dummy(data)
theDict=a.getDict()
You can make the dict accessible with dot notation, as if it were a class instance, like this.
class dummy:
def __init__(self, my_dict):
self.my_dict = my_dict
I got a small python code but not understand how it works:
import xmlrpclib
class PoolTest:
def __init__(self, url):
self.proxy = xmlrpclib.ServerProxy(url, allow_none=True)
def add(self, asset):
s = asset.marshal()
self.proxy.add(s)
def delete(self, asset):
s = asset.marshal()
self.proxy.delete(s)
I don't understand the way to set these:
self.proxy.add(s)
self.proxy.delete(s)
It looks like recursion but it seems not. Can anybody help me to clear that?
I would like some advice on how to best design a class and it's instance variables. I initialize the class with self.name. However, the main purpose of this class it to retrieve data from an API passing self.name as a parameter, and then parsing the data accordingly. I have a class method called fetch_data(self.name) that makes the API request and returns ALL data. I want to store this data into a class instance variable, and then call other methods on that variable. For example, get_emotions(json), get_personality_traits(json), and get_handle(json), all take the same dictionary as a parameter, assign it to their own local variables, and then manipulate it accordingly.
I know I can make fetch_data(self.name) return data, and then call fetch_data(self.name) within the other methods, assign the return value to a local variable, and manipulate that. The problem is then I will need to call the API 5 times rather than 1, which I can't do for time and money reasons.
So, how do I make the result of fetch_data(self.name) global so that all methods within the class have access to the main data object? I know this is traditionally done in an instance variable, but in this scenario I can't initiliaze the data since I don't have it until after I call fetch_data().
Thank you in advance!
It seems like you just need to do something like this:
class Foo(object):
def __init__(self, name):
self.name = name
self.data = None
def fetch_data(self):
if self.data is None:
# Only call the API once
self.data = self.really_fetch_data()
return self.data
def get_emotions(self):
emotions = self.fetch_data().get("emotions")
...
Why don't you just try to solve this as you described?
For example, you can take this as a starting point:
import json
class APIBundle(object):
def __init__(self, name):
self.name = name
self.data = None
self.update()
def update():
response = json.loads(API_request(self.name))
# Do some parsing on response
self.data = response
def get_emotions():
# Work through current data state
# and filter as desired
result = []
for message in self.data['messages']:
if message.find(':)') != -1:
result.append((message, 'positive'))
if message.find(':(') != -1:
result.append((message, 'negative'))
return result
if __name__ == '__main__':
ab = APIBundle('my-secret-name')
print(self.get_emotions())
Try to do it with self.data=None , or make an instance variable and call whenever you need. writing algorithm will make this thing more complex try to solve issue with inbuilt functions or with algorithm program vulnerability will affect alot.