Python-命名空间

201 阅读1分钟

命名空间

X=11

def f():
	print(X)
	
def g():
	X=22
	print(X)

class C:
	X=33
	def m(self):
		X=44
		self.X=55
		

if __name__=='__main__':
	print(X)		#11
	f()				#11
	g()
	print(X)		#22
	
	obj=C()			
	print(obj.X)	#33
	
	obj.m()			
	print(obj.X)	#55
	print(C.X)		#33
	



命名空间字典

>>> class super:
	def hello(self):
		self.data1='spam'

		
>>> class sub(super):
	def hola(self):
		self.data2='eggs'

		
>>> X=sub()
>>> X.__dict__
{}
>>> X.__class__
<class '__main__.sub'>
>>> sub.__bases__
(<class '__main__.super'>,)
>>> super.__bases__
(<class 'object'>,)
>>> 

>>> class super:
	def hello(self):
		self.data1='spam'

		
>>> class sub(super):
	def hola(self):
		self.data2='eggs'

		
>>> X=sub()
>>> X.__dict__
{}
>>> X.__class__
<class '__main__.sub'>
>>> sub.__bases__
(<class '__main__.super'>,)
>>> super.__bases__
(<class 'object'>,)
>>> Y=sub()
>>> X.hello()
>>> X.__dict__
{'data1': 'spam'}
>>> X.hola()
>>> X.__dict__
{'data1': 'spam', 'data2': 'eggs'}
>>> sub.__dict__.keys()
dict_keys(['__module__', 'hola', '__doc__'])

>>> super.__dict__.keys()
dict_keys(['__module__', 'hello', '__dict__', '__weakref__', '__doc__'])
>>> Y.__dict__
{}
>>> X.data1,X.__dict__['data1']
('spam', 'spam')
>>> X.data3='toast'
>>> X.__dict__
{'data1': 'spam', 'data2': 'eggs', 'data3': 'toast'}
>>> x.__dict__['data']='ham'
Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    x.__dict__['data']='ham'
NameError: name 'x' is not defined
>>> X.__dict__['data3']='ham'
>>> X.data3
'ham'
>>> X.__dict__,Y.__dict__
({'data1': 'spam', 'data2': 'eggs', 'data3': 'ham'}, {})
>>> dir(X)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'data1', 'data2', 'data3', 'hello', 'hola']

>>> dir(sub)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'hello', 'hola']
>>> dir(super)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'hello']
>>>