Python 面向对象类

Table of Contents

 

1. 注意事项 

2. 类的定义

3. 类的方法

4. 内部类的使用

5. 方法的动态特性


1. 注意事项 

1.1. 类的私有成员以两个下划线开始“__”,如下面的"__color";
1.2. 私有属性的访问方式:instance._classname_attribute;

2. 类的定义

class Fruit:
    """This is Class Fruit"""
    price = 0   #属性

    def __init__(self): #构造函数
        self.__color = "red"  #定义私有变量:实例属性(私有)
        self.color = "black" #定义公有变量:实例属性(公共)
        zone = "China"

if __name__ == "__main__":
    print("step1:" + str(Fruit.price))  #使用类名调用变量

    apple = Fruit() #实例化类的一个对象apple

    print("step2:" + str(apple.price)) #打印apple对象的price

    Fruit.price = Fruit.price + 10

    print("step3:" + str(apple.price))  # 打印apple对象的price

    print("step4:" + apple.color)  # 打印apple对象的price

    #print(apple.__color)  # 报错:“AttributeError: 'Fruit' object has no attribute '__color'”
    print("step5:" + apple._Fruit__color) #打印私有属性值

 

结果:

C:\Python\Python38\python.exe "E:/python/python project/hello world.py"
step1:0
step2:0
step3:10
step4:black
step5:red
step6:
(<class 'object'>,)
step7:
{'_Fruit__color': 'red', 'color': 'black'}
step8:
__main__
step9:
This is Class Fruit

3. 类的方法

类的方法分为公有和私有方法,Python使用函数staticmethod()或@staticmethod修饰器把普通的函数转换为静态方法。Python的静态方法并没有和类的实例进行名称绑定,要调用只需使用类名作为它的前缀即可

代码:

class Book:
    """This is book class!"""
    price = 0   #定义全局变量

    def __init__(self):
        self.color = "read"

    def getColor(self): #公共函数
        print("Function getPrice(): color=%s" % self.color)
        return self.color;

    @staticmethod   #私有函数
    def getPrice():
        Book.price += 10
        print("Function getPrice(): price=%d" % Book.price)

    def __getPrice(): #私有函数,注意没有self
        print("Function __getPrice(): price=%d" % Book.price)
    count = staticmethod(__getPrice)

if __name__ == "__main__":
    python = Book()
    python.getColor()
    python.getPrice()
    Book.count()
    python.count()

结果:

C:\Python\Python38\python.exe "E:/python/python project/hello world.py"
Function getPrice(): color=read
Function getPrice(): price=10
Function __getPrice(): price=10
Function __getPrice(): price=10

4. 内部类的使用

5. 方法的动态特性

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值