#构造方法 __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());
python之方法和属性
最新推荐文章于 2021-01-29 06:23:33 发布