Python练习代码 -- 类

来源:互联网 发布:域名注册百度 编辑:程序博客网 时间:2024/05/07 10:04


# -*- mode: python; coding: utf-8 -*-class Fruit:    type = 1  #类属性,相当于静态变量            #构造函数    def __init__(self):        self.price = 5    #实例属性,实例化对象后才能调用        self.__color = "red" #私有属性命名 __开头    def getColor(self, strx):  #实例方法,隐含参数self为类的实例        return self.__color        @staticmethod     def printVer():  #声明为静态方法,无隐含参数        print("Version: %d" %(Fruit.type))    @classmethod    def printVer2(cls):  #声明为类方法,隐含参数cls为类        print(cls)    #析构函数    def __del__(self):        self.__color = ""        print("free")        Fruit.printVer()Fruit.printVer2()fruit = Fruit();fruit.type = 2  #通过实例并不能改变类属性,实例这时候会创建一个typeprint(Fruit.type)  #-->1    print(fruit.price)print(fruit.getColor("xxx"))    print(fruit._Fruit__color)  #直接调用私有属性    






0 0
原创粉丝点击