Python类

来源:互联网 发布:淘宝春节发货通知 编辑:程序博客网 时间:2024/05/29 10:59

类和对象

类的定义:
class Fruit:def __init__(self):self.name = "name"self.color = "color"def grow(self):print("Fruit grow...")
属性和方法:
<pre name="code" class="python">class Fruit :    price = 0    def __init__(self):        self.color = "red"        zone = "China"    def grow(self):        print("Fruit grow...")if __name__ == "__main__":    print(Fruit.price)    apple = Fruit()    print(apple.color)    Fruit.price = Fruit.price + 10    print("apple's price:" + str(apple.price))    banana = Fruit()    print("banana's price:" + str(banana.price))#输出结果:0redapple's price:10banana's price:10


不提倡的访问私有属性方法:
class Fruit:def __init__(self):self.__color = "red">>>print(Fruit.__color)  #不能直接访问私有变量Traceback (most recent call last):  File "<pyshell#23>", line 1, in <module>    print(Fruit.__color)AttributeError: type object 'Fruit' has no attribute '__color'>>> apple = Fruit()  #仅在开发或者调试阶段使用>>> print(apple._Fruit__color)red


类的一些内置属性,用来管理类的内部关系:
如__dict__,__bases__,__doc__等;
class Fruit:    def __init__(self):        self.__color = "red"class Apple(Fruit):    """This is doc"""    passif __name__ == "__main__":    fruit = Fruit()    apple = Apple()    print(Apple.__bases__)  输出基类组成的元祖    print(apple.__dict__)   #输出属性组成的字典    print(apple.__module__)  #输出类所在的模块名    print(apple.__doc__)  #输出doc文档输出结果:(<class '__main__.Fruit'>,){'_Fruit__color': 'red'}__main__This is doc


类的方法:
类的方法分为公有方法和私有方法;私有方法不能被模块外的类或方法调用,也不能被外部的类或函数调用。

静态方法使用:
Python使用staticmethod()或@staticmethod修饰器把普通的函数转换为静态方法。
class Fruit:    price = 0  #类变量        def __init__(self):        self.__color = "red"    def getColor(self): #打印私有变量方法        print(self.__color)    @ staticmethod    def getPrice():        print(Fruit.price)    def __getPrice():  #定义私有函数        Fruit.price = Fruit.price + 10        print(Fruit.price)    count = staticmethod(__getPrice)  #使用staticmethod方法定义静态方法    if __name__ == "__main__":    apple = Fruit()    apple.getColor()  #用实例调用静态方法    Fruit.count()  #用类名调用静态方法    banana = Fruit()    Fruit.count()    Fruit.getPrice()输出结果:red102020


类的方法至少需要1个参数,调用方法时不必给该参数赋值,通常这个特殊的参数被命名为self,self参数表示指向实例对象本身,
self参数用于区分函数和类的方法,self必须显示使用,因为python是动态语言,无法知道在方法中药赋值的变量是不是局部变量或是
需要保存成实例属性;


类方法:类方法是将类本身作为操作对象的方法,使用函数classmethod()或@classmethod修饰器定义;
与实例方法不同的是把类作为第一个参数(cls)传递;
如果某个方法需要被其他实例共享,同时又需要使用当前实例的属性,则定义为类方法;
@ classmethoddef getPrice(cls):      print(cls.price)      def __getPrice(cls):      cls.price = cls.price + 10      print(cls.price)    count = classmethod(__getPrice)  #定义类方法


__init__方法:构造函数用于初始化类的内部状态,为类的属性设置默认值。
class Fruit:    def __init__(self,color):        self.__color = color        print(self.__color)    def getColor(self):        print(self.__color)    def setColor(self,color):        self.__color = color        print(self.__color)if __name__ == "__main__":    color = "red"    fruit = Fruit(color)    fruit.getColor()    fruit.setColor("Blue")输出结果:redredBlue

__del__方法:析构函数可以显示释放对象占用的资源,

垃圾回收机制:
Python提供了gc模块释放不再使用的对象,采用的是引用计数方式,函数collect()可以一次性收集所有待处理的对象。
import gcclass Fruit:    def __init__(self,name,color):        self.__name = name        self.__color = color    def getColor(self):        return self.__color    def setColor(self,color):        self.__color = color    def getName(self):        return self.__name    def setName(self,name):        self.__name = nameclass FruitShop:    def __init__(self):        self.fruit = []    def addFruit(self,fruit):        fruit.parent = self        self.fruit.append(fruit)if __name__ == "__main__":    shop = FruitShop()    shop.addFruit(Fruit("apple","red"))    shop.addFruit(Fruit("banana","yellow"))    print(gc.get_referrers(shop))   #打印出shop关联的所有对象    del shop   #删除shop对象,但是shop对象关联的其他对象并没有被释放    print(gc.collect())   #显示调用垃圾回收器释放shop对象关联的其他对象

类的内置方法:

__new__()
在__init__()之前被调用,用于创建实例对象。

__getattr__(),__setattr__(),__getattribute__()
.......







每个class语句会生成一个新的对象;

每次类调用时就会生成一个新的实例对象;实例自动连接至创建了这些实例的类;

类连接至其基类的方式是将基类列在类头部的括号内,从左至右的顺序会决定树中的次序;


属性通常是class语句中通过赋值语句添加在类中,而不是嵌入在函数发def语句类;

属性通常是在类内,对传给函数的特殊参数(也就是self),做赋值运算而添加在实例中;



0 0