Python 面向对象编程

来源:互联网 发布:计算机美工专业 编辑:程序博客网 时间:2024/05/29 16:14
# python 中类的使用, 对象的使用, 属性和类属性的区别  
class Fruit:
    price = 0

    def __init__(self):
        self.color = "red"
        zone = "china"


if __name__ == '__main__':
    print Fruit.price
    apple = Fruit()
    print apple.color
    Fruit.price = Fruit.price + 10
    print "apple price " + str(apple.price)
    banana = Fruit()
    print  "banana 's price " + str(banana.price)

Python 的属性分为实例属性和静态属性, 实例属性是self 为前缀的属性, __init__ 方法就是python的构造函数, 如果__init__方法中定义的变量没有使用self 作为前缀说明, 则该变量只是普通的局部变量, 类中其他方法定义的变量也只是局部变量。

默认的__color 属性是私有的属性, 如果访问私有属性的话则会出现错误 :

# -*- coding:utf8 -*-
__author = 'shencheng'

# python 中类的使用, 对象的使用, 属性和类属性的区别
class Fruit:
    price = 0
    __color="red"
    def __init__(self):
        self.color = "red"
        zone = "china"


if __name__ == '__main__':
    print Fruit.__color
    print Fruit.price
    apple = Fruit()
    print apple.color
    Fruit.price = Fruit.price + 10
    print "apple price " + str(apple.price)
    banana = Fruit()
    print  "banana 's price " + str(banana.price)

上面代码会出现问题:

Traceback (most recent call last):
  File "C:/Users/shencheng/PycharmProjects/Widget/baselan/langbase.py", line 14, in <module>
    print Fruit.__color
AttributeError: class Fruit has no attribute '__color'

# python 中类的使用, 对象的使用, 属性和类属性的区别
class Fruit:
    price = 0
    #    __color="red"
    def __init__(self):
        self.__color = "red"

class Apple(Fruit):
    pass

if __name__ == '__main__':
    fruit = Fruit()
    apple = Apple()
    print Apple.__bases__
    print apple.__dict__
    print apple.__module__

# python 中类的使用, 对象的使用, 属性和类属性的区别
class Fruit:
    price = 0

    def __init__(self):
        self.__color = "red"

    def getColor(self):
        print self.__color

    @staticmethod
    def getPrice():
        print Fruit.price

    def __getPrice(self):
        Fruit.price = Fruit.price + 10

    count = staticmethod(__getPrice())


if __name__ == '__main__':
    apple = Fruit()
    apple.getColor()
    Fruit.cout()
    banana = Fruit()
    Fruit.cout()
    Fruit.getPrice()


# __del__的使用方法 , 会在程序结束的时候做一次析构的操作
class Fruit:
    def __init__(self, color):
        self.__color = color
        print self.__color

    def __del__(self):
        self.__color = ""
        print "free"

    def grow(self):
        print "grow"


if __name__ == '__main__':
    color = "red"
    f = Fruit(color)
    f.grow()


  对于C++ 语言析构函数是必须的,程序员需要为对象分配内存空间, 同事也要手动释放内存, 使用python 编写程序不考虑后台的内存管理, 直接面对程序逻辑

#由于类的__init__ 只能初始化一次, 所以两个雷的话只有一个可以被调用
class Fruit(object):
    def __init__(self):
        print "init fruit"
    def grow(self):
        print "grow"

class Vegetable(object):
    def __init__(self):
        print "init vegetable"
    def plant(self):
        print "plant"

class WaterMelen(Fruit, Vegetable):
    pass
if __name__ == '__main__':
    w = WaterMelen()
    w.grow()
    w.plant()


0 0
原创粉丝点击