coding=utf-8 #author = 'pengwei' class People: name = 'jack' # public age = 12 # private def printName(self): print(self.name) def getAge(self): return self.age #构造函数 def init(self, name, age): self.name = name self.age = age #析构函数 def __del(self): self.name = None p = People('pw', 12) p.printName()
定义成员变量时,不带_ (如上例name)默认为public,_age为private
构造函数为 init 析构函数为del
这么定义静态static方法?
对象方法有self参数,类方法有cls参数,静态方法是不需要这些附加参数的。
class A(object): "This ia A Class" @staticmethod # 静态方法 def Foo1(): print("Call static method foo1()\n") @classmethod def Foo2(cls): # 类的方法 print("Call class method foo2()") print("cls.name is ",cls.name) A.Foo1(); A.Foo2();
结果是:
Call static method foo1()
Call class method foo2()
cls.name is A