I'm looking at a case like this:
def parse_item(self, response):
item = MetrocItem()
def ver(string):
if string:
return string
else:
return 'null'
item['latitude'] = ver(response.xpath('//input[@id="latitude"]/@value').extract_first())
It works, but is there a better way to do this?
To call a function within class with Python, we call the function with self before it. We call the distToPoint instance method within the Coordinates class by calling self. distToPoint . self is variable storing the current Coordinates class instance.
The main reason people use classes (that I've read) is for re-usability, but you can call a function any number of times. The main other reason I've seen is because you can create different instances of classes, but you can call functions with different parameters.
Show activity on this post. Yes you can definitely have functions outside of a class.
Object-oriented programming (OOP) is a computer programming model that organizes software design around data, or objects, rather than functions and logic.
As @Graipher mentioned in the comments, this is certainly valid in some cases, but in your particular case, it is unnecessary. If your function depends on a local variable, then you're returning a closure that needs to be reconstructed every time you call the method. But in your case, the function is going to behave the same way every time you call the method, so it would make more sense to define it globally as a private method, or even as a lambda in your case.
ver = lambda x: x if x else 'null'
But the preferred approach would be to simply define it globally and start the name with an underscore to make the intention clear.
def _ver(string):
...
You can get rid of that function completely:
string = response.xpath('//input[@id="latitude"]/@value').extract_first()
item['latitude'] = string if string else 'null'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With