私有属性_x
class Rectangle:
def init(self):
self.width = 0
self.height = 0
def setSize(self, size):
self.width, self.height = size # 使两个值都等于size
def getSize(self):
return self.width, self.height
size = property(setSize, getSize) # property函数
r = Rectangle()
r.width = 10
r.height = 20
print(r.getSize())
r.setSize((150, 100))
print(r.height)
静态方法和类成员方法,
class Myclass():
@staticmethod
def smeth():
print(“this is a static method”)
# smeth=staticmethod(smeth)#静态方法,没有self参数,能够被类本身直接调用,装入staticmethod
@classmethod # 装饰器,在方法上方将装饰器列出,指定多个装饰器时,应用顺序与指定顺序相反
def cmeth(cls):
print("this is a class method of", cls)
# cmeth=classmethod(cmeth)#类成员方法,用看类的具体对象调用,cls参数是自定被绑定到类的
Myclass.smeth()
Myclass.cmeth()
getattr,setattr
class Rectangle():
def init(self):
self.width = 0
self.height = 0
def __setattr__(self, name, value):
if name == 'size':
self.width, self.height = value
else:
self.__dict__[name] = value
def __getattr__(self, name):
if name == 'size':
return self.width, self.height
else:
return AttributeError
迭代器_iter_返回一个迭代器,就是next()方法
class Fibs:
def init(self, n=10000):
self.a = 0
self.b = 1
self.n = n
def __iter__(self):
return self
def __next__(self):
self.a, self.b = self.b, self.a + self.b
if self.a > self.n:
raise StopIteration
return self.a
fibs = Fibs()
for f in fibs:
# print(f)
if f > 1001:
print(f)
# continue
break