python之方法和属性

#构造方法 __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());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值