test.py
def test():
print "test is running"
if __name__ == "__main__":#自运行时调用该程序块
print "test main is working"
else:
print "test run is not main"
if __name__ == "test":#import 时调用该程序块
print "test is invoked"
输出
$ python test.py
test main is working
$ python
>>> import test
test run is not main
>>>t = test
>>>t.test()
test is running
>>>
使用模块的__name__
#!/usr/bin/python
# Filename: using_name.py
if __name__ == '__main__':
print 'This program is being run by itself'
else:
print 'I am being imported from another module'
输出
$ python using_name.py
This program is being run by itself
$ python
>>> import using_name
I am being imported from another module
>>>
2, self and class method 类方法; 对象方法
Python语言里面有这样的规定:方法不能在不通过实例的情况下被调用,即方法必须被绑定(到一个实例)以后才能被直接调用,Python语言不支持静态方法(也就是静态成员函数),在需要有静态方法提供的功能时可以用一个全局函数来绕过这个限制.
类的变量 由一个类的所有对象(实例)共享使用。只有一个类变量的拷贝,所以当某个对象对类的变量做了改动的时候,这个改动会反映到所有其他的实例上。
对象的变量 由类的每个对象/实例拥有。因此每个对象有自己对这个域的一份拷贝,即它们不是共享的,在同一个类的不同实例中,虽然对象的变量有相同的名称,但是是互不相关的。 例如: self.mymem='my test'
对于一个类C来说,下面列出了C的全部特殊属性:
C.__name__ 类C的字符串名字
C.__doc__ 类C的文档字符串
C.__bases__ 类C的父类的列表
C.__dict__ 类C的属性
C.__module__ 对类C进行定义的模块
class Person:
#class method
def saybye(cls):
print 'hello,bye'
def sayHi(self):
print 'Hello,how are you?'
p=Person()
Person.sayHi(p)
p.sayHi()
Person.saybye(p)
p.saybye()
本文介绍了Python中__name__属性的作用及其在模块导入时的行为差异,并详细解释了类方法与对象方法的区别及使用场景。通过示例代码展示了如何使用__name__判断模块是否作为主程序运行,以及类方法的定义和调用方式。
1072

被折叠的 条评论
为什么被折叠?



