Python类1

类:
类的方法必须有一个self参数,但是在方法调用时可以不传递这个参数:
Python的任何类型都是对象,包括字符串类型,数字类型,内置类型;
Python构造函数:__init__
函数、方法或属性的名字以两个下划线开始,则表示私有类型。没有使用两个下划线开始则表示共有类型;


<span style="font-size:18px;">class fruit(object):
    price = 0	#类属性
    def __init__(self):
        self.color = 'red'	#实例属性
        size = 10
if __name__ == '__main__':
    apple = fruit()
    print 'apple',apple.price
    print apple.color
    apple.price = 20
    print 'apple',apple.price
    apple.color = 'yellow'
    fruit.price = 25
    fruit.color = 'blue'
    print apple.color
banana = fruit()
print '==================='
print banana.price
print banana.color


red
apple 20
yellow
===================
25
red
</span>



Python 的类和对象都可以访问类属性,而java中的静态变量只能被类调用;


类的内置属性:
class Apple(fruit):
    pass
print Apple.__bases__
print Apple.__dict__
print Apple.__module__
print Apple.__doc__


Python的静态方法并没有和类的实例进行名称绑定,Python的静态方法相当于全局函数。
class fruit1():
    price = 0;
    
    def __init__(self):
        self.__color = 'blue'
    def getcolor(self):
        print self.__color
    @staticmethod
    def getprice():
        print fruit1.price
    def __getprice():
        fruit1.price = fruit1.price+10
        print fruit1.price
        #print fruit.__color
    count = staticmethod(__getprice)
if __name__ == '__main__':
    apple = fruit1()
    apple.getcolor()
    fruit1.count()
    banana = fruit1()
    fruit1.count()
    fruit1.getprice()
输出:
blue
10
20
20



内部类:
1、直接使用外部类调用内部类,生成内部类的实例,再调用内部类的方法。
2、先对外部类进行实例化,然后再实例化内部类,最后调用内部类方法。
__init__:构造函数
用于定义实例变量
用于程序的初始化
__del__:析构函数
用于释放对象占用的资源
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Car12

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值