Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a bad programing practice to put a function inside a class method?

Tags:

python

oop

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?

like image 671
Emiliano Isaza Villamizar Avatar asked Apr 16 '18 15:04

Emiliano Isaza Villamizar


People also ask

Can you call a function inside a class?

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.

Why do we use class instead of function?

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.

Can methods be outside a class?

Show activity on this post. Yes you can definitely have functions outside of a class.

Does oop use function?

Object-oriented programming (OOP) is a computer programming model that organizes software design around data, or objects, rather than functions and logic.


2 Answers

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):
    ...
like image 57
Silvio Mayolo Avatar answered Oct 08 '22 06:10

Silvio Mayolo


You can get rid of that function completely:

string = response.xpath('//input[@id="latitude"]/@value').extract_first()
item['latitude'] = string if string else 'null'
like image 2
Niklas Mertsch Avatar answered Oct 08 '22 04:10

Niklas Mertsch