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'>  

问题评论:

1  
Couldn’t a function return a class?
1  
indeed it could. however, it prints a class which has same name just as the function. i am expecting a class that has different name
– avalanche
25 mins ago
    
OpenCV is written in C++ by the way

答案:

答案1:

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.

答案评论:

答案2:

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'>

答案评论:

答案3:

Answer

Yes, they can have same name, if they are situated in different scopes.

Example:

one.py:

def A():
    pass

two.py:

class A():
    pass

Let’s check:

>>> import one
>>> one.A
<function A at 0x7f1b9f132b70>
>>> import two
>>> two.A
<class 'two.A'>

答案评论:

    
it’s from the same file though.
    
@timgeb module != file (specially with C extensions).
    
@brunodesthuilliers the documentation defines a module as a file containing Python definitions and statements.
    
@timgeb cv is a package

原文地址:

https://stackoverflow.com/questions/47756183/can-a-class-and-a-function-have-a-common-name-in-python

添加评论