Python Special Syntax 6:模块的__name__

#-*-coding:utf-8
class Person:
    __privateName=None;

    count=0;#既可以被实例对象引用,也可以被当做静态对象引用,NND,好混乱。

    def __init__(self,name):
        self.count+=1
        Person.count+=2
        print(%s has been created % name)
        self.__privateName=name;
        self.name=name

    def printPrivateName(self):
        print(Private Name: %s %  self.__privateName)

    def printName(self):
        print(Name is %s % self.name)

if  __name__==__main__:
    zili=Person(zili)
    Person.__privateName=zhangsan
    print(Person.__privateName)
    zili.__privateName=zhangsan
    print(jiangyao shuchu :%s % zili.__privateName)
    zili.printName()
    zili.printPrivateName()
    print(zili.count)
    print(Person.count)
    Person.ABC=abcvalue
    print(Person.ABC)
else:
    print("I‘m importing by some other guys.")

独立运行这个文件的时候__name__是‘__main__‘,在被别的Python  import的时候,就会执行else块,在继承体系中恰当运用可以非常好的协同工作。

 

说到协同工作这几个字,真感觉这个设计是Python的天才式设计。

Python Special Syntax 6:模块的__name__,布布扣,bubuko.com

Python Special Syntax 6:模块的__name__

上一篇:FAQ: Python中if __name__ == '__main__':作用


下一篇:【python核心编程】第六章 序列