Can a class and function have a common name in Python?

It looks like there is a function as well as a class associated with the name cv2.VideoCapture.

Is it possible for a class and function that have a common name?

I assume that at the moment cv2.VideoCapture represents a class and a function.

>>>import cv2

>>>print(cv2.VideoCapture)
<built-in function VideoCapture>  

>>>camera = cv2.VideoCapture(0)  
>>>print(type(camera))
<class 'cv2.VideoCapture'>  
+4
source share
2 answers

It all depends on what you call the "name" ...

>>> class Foo(object):
...     pass
... 
>>> _Foo = Foo
>>> def Foo():
...     return _Foo()
... 
>>> f = Foo()
>>> print(Foo)
<function Foo at 0x7f74a5fec8c0>
>>> print(type(f))
<class '__main__.Foo'>
>>> 

As you can see, here you have a function that displays like Fooand having it __name__== "Foo", and a class that is open as _Foo, but having __name__== "Foo".

: (= > ), . , .__name__.

+5

OpenCV, , , , .

cv2.py

def VideoCapture(_):
    class VideoCapture(object):
        pass
    return VideoCapture()

:

>>> import cv2
>>> cv2.VideoCapture
<function VideoCapture at 0x7f70d36069b0>
>>> 
>>> camera = cv2.VideoCapture(0)
>>> type(camera)
<class 'cv2.VideoCapture'>
+2

Source: https://habr.com/ru/post/1690563/


All Articles