python12day

私有属性_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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值