简体   繁体   中英

Python class and namespace?

lets say I wanna define a class name MyClass.

and I wanna use that class. so,

class MyClass():

    blabla

MyClass = MyClass(abc)

say I wanna make a function and use MyClass in that function. What I found out is that the following code will through an exception :

def MyFunction():
    MyClass = MyClass(abc)

MyFunction(123)

any help? I can do like

    Myclass1 = MyClass(abc)

but I think I'm missing something basic about namespaces. thank you!

When you execute

MyClass = MyClass(abc)

you are creating a new instance of MyClass , and assigning it to the class itself, whereas with Myclass1 = MyClass(abc) , you don't overwrite the class. Overwriting the class shouldn't throw an exception (the exception may be to do with calling your MyFunction() method with an argument, since it doesn't take any, or perhaps calling the constructor of MyClass with an argument, since that doesn't take any either), but I imagine it isn't what you intend to do.

Myclass1 = MyClass(abc) looks alright to me (besides the argument being passed), although I would recommend using myClass1 (or even better, the generally used python style of my_class1 ) for variables, rather than capitalizing the fist letter, as it prevents confusion about which object is a class.

MyClass = MyClass(abc)

The above line is the same as doing this:

def x():
   print 'Hello'
   return 'Hello'

x() # outputs Hello
x = x() # Also ouputs 'Hello' (since x() is called)
x() # Error, since x is now 'Hello' (a string), and you are trying to call it.

In python the name of a variable is just a pointer to a place in memory. You can freely assign it to another location (object) by pointing it to something else. In fact, most things you define work that way (like methods and classes). They are just names.

Its even stranger if your method doesn't have a return value (like most class __init__ methods). In that case, the left hand side is None , and you'll get TypeError: 'NoneType' object is not callable . Like this:

>>> def x():
...   print 'Hello'
...
>>> x()
Hello
>>> x = x()
Hello
>>> x()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
>>> type(x)
<type 'NoneType'>

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