简体   繁体   中英

Can a class and a 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 a function that share a common name?

My guess is that at this moment cv2.VideoCapture represents a class and a function as well.

>>>import cv2

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

>>>camera = cv2.VideoCapture(0)  
>>>print(type(camera))
<class 'cv2.VideoCapture'>  

All depends on what you call "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, you here have a function exposed as Foo and having it's __name__ == "Foo", and a class exposed as _Foo but having __name__ == "Foo" too.

To answer your question: you cannot have the same name (=> variable) bound to more than one object at a given time in a given namespace. But you can have has many objects has you want having the same value for a .__name__ attribute.

I have not checked the OpenCV source code in order to check out what or why is going on in this specific case, but in theory this can be possible if your function returns an instance of a class with the same name.

consider the file cv2.py with the following content

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

usage:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM