python 类变量,Python类1

 2023-09-25 阅读 16 评论 0

摘要:类: 类的方法必须有一个self参数,但是在方法调用时可以不传递这个参数: Python的任何类型都是对象,包括字符串类型,数字类型,内置类型; Python构造函数:__init__ 函数、方法或属性的名字以两个下划线开始,则表
类:
类的方法必须有一个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.priceprint apple.colorapple.price = 20print 'apple',apple.priceapple.color = 'yellow'fruit.price = 25fruit.color = 'blue'print apple.color
banana = fruit()
print '==================='
print banana.price
print banana.colorred
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@staticmethoddef getprice():print fruit1.pricedef __getprice():fruit1.price = fruit1.price+10print fruit1.price#print fruit.__colorcount = 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__:析构函数
用于释放对象占用的资源

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/94138.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息