Python面向对象(二):字段、方法、(属性)

这里写图片描述
静态字段内存中只保存一份
普通字段每个对象中都要保存一份

class Company:
    place='America'   #静态字段
    def __init__(self,name):
        self.name=name   #普通字段
        
obj=Company('Google')
print(obj.name)   #直接访问普通字段
print(Company.place)   #直接访问静态字段

#Output:
#Google
#America

这里写图片描述
普通方法:由对象调用;至少一个self参数;执行普通方法时,自动将调用该方法的对象赋值给self
类方法:由类调用;至少一个cls参数;执行类方法时,自动将调用该方法的类复制给cls
静态方法:由类调用;无默认参数

class testfun:
    def __init__(self,tool):
        self.tool=tool
    def ordinary_fun(self):   #定义普通方法
        print('ordinary method')
        
    @classmethod
    def class_fun(cls):   #定义类方法
        print('class method')
    
    @staticmethod
    def static_fun():   #定义静态方法
        print('static method')
        
tt=testfun('bike')
tt.ordinary_fun()   #调用普通方法
testfun.class_fun()   #调用类方法
testfun.static_fun()   #调用静态方法

#Output:
#ordinary method
#class method
#static method

Python中的属性其实是普通方法的变种

class profun():
    def fun(self):   #定义普通方法
        print('test ordinary fun OK!')
    
    @property
    def prop(self):   #定义属性
        print('test prop OK!')
    
testobj=profun()
testobj.fun()   #调用普通方法
testobj.prop   #调用属性

#Output:
#test ordinary fun OK!
#test prop OK!

定义属性时,在普通方法的基础上添加 @property 装饰器,仅有一个self参数;
调用属性时,无需括号

class book():
    def __init__(self,chapter_now,page_read):
        self.chapter_now=chapter_now   #当前读到章节
        self.page_read=page_read
        self.each_chapter=100   #每张默认100页
    
    @property
    def endpage(self):
        num=(self.chapter_now-1)*self.each_chapter+self.page_read
        return num
    
obj=book(2,35)
obj.endpage

#Output:
#135
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值