python之方法和属性

来源:互联网 发布:计算机网络考研 知乎 编辑:程序博客网 时间:2024/05/17 08:44
#构造方法 __init__(self)class  bird:    def __init__(self):        self.hunger = True;    def eat(self):        if(self.hunger):            print("Aaaah....");            self.hunger = False;        else:            print("No. thanks");B = bird();print(B.eat());print(B.eat());#继承##不可以调用A.eat();class songbird(bird):    def __init__(self):self.sound = "squawk!";    def sing(self): print(self.sound);A = songbird();A.sing();A.sing();#调用未绑定的超类构造方法__metaclass__=type #super函数只在新式类中起作用class  bird:    def __init__(self):        self.hunger = True;    def eat(self):        if(self.hunger):            print("Aaaah....");            self.hunger = False;        else:            print("No. thanks");class songbird(bird):    def __init__(self):        super(songbird, self).__init__();        self.sound = "squawk!";    def sing(self):        print( self.sound );A = songbird();A.sing();A.eat();#访问属性class  rectange:    def __init__(self):        self.width = 0;        self.height = 0;    def setsize(self, size):        self.width , self.height = size;    def getsize(self):        return self.width, self.height;r = rectange();r.width = 10;       #可以访问属性r.height = 5;print(r.width, r.height);r.setsize([100, 50]);print(r.getsize());#property函数的使用__mataclass__= type; #新式类class  rectange:    def __init__(self):        self.width = 0;        self.height = 0;    def setsize(self, size):        self.width , self.height = size;    def getsize(self):        return self.width, self.height;    size = property(getsize, setsize);r = rectange();r.width = 10;r.height = 5;print(r.size);r.size = [100, 50];print(r.width);#静态方法和类成员方法#静态方法:定义时没有self参数,能被类本身直接调用#类成员方法:定义时有参数cls,能被类直接调用;##方法一:装入statimethod和classmethod类型__mataclass__ = type;class myclass:    def smeth():        print("that is a static method");    smeth = staticmethod(smeth);    def cmeth(cls):        print("that is a class method of ,", cls);    cmeth = classmethod(cmeth);print(myclass.smeth());print(myclass.cmeth());##方法二:使用@操作符,在方法的上方将装饰器列出__mataclass__ = type;class myclass:    @staticmethod    def smeth():        print("that is a static method");   # smeth = staticmethod(smeth);    @classmethod    def cmeth(cls):        print("that is a class method of ,", cls);    #cmeth = classmethod(cmeth);print(myclass.smeth());print(myclass.cmeth());

0 0
原创粉丝点击