类与对象小解-python

首先看一个例子:

  • #coding=UTF-8 不懂啥意思
    
    class Robot:
        """表示一个带有名字的机器人"""
        #一个类变量,用来计数机器人的数量
        population = 0
    
        def __init__(self,name):
            self.name = name
            print('(Initializing {})'.format(self.name))
            #当有人被创建时,机器人将会增加数量
            Robot.population += 1
    
        def leave(self):
            """I died."""
            print('{} is being destryed'.format(self.name))
            Robot.population -= 1
    
            if Robot.population == 0:
              print("{} was the last robot".format(self.name))
            else:
                print('There are still {:d} robots working'
                      .format(Robot.population))
    
        def say_hi(self):
            """The honest hello from robot"""
            print('Greetings, my master call me {}'.format(self.name))
    
        #
        @classmethod
        def how_many(cls):
            """Print the number of rest Robots"""
            print('We have {:d} robots left'.format(Robot.population))
    
    summer1 = Robot("Sun")
    summer1.say_hi()
    Robot.how_many()
    
    summer2 = Robot("star")
    summer2.say_hi()
    Robot.how_many()
    
    summer3 = Robot("moon")
    summer3.say_hi()
    Robot.how_many()
    
    print('\nRobots can play with you.\n')
    
    print('Robots want to play with themselves and living you now.')
    summer1.leave()
    summer2.leave()
    summer3.leave()
    
    Robot.how_many()
    

在此程序里,我们可以看到population 属于 Robot 类,因此它是一个类变量。 name 变量属于一个对象(通过使用 self 分配) ,因此它是一个对象变量。

看类与对象的定义:

类和对象(class)是两种以计算机为载体的计算机语言的合称。对象是对客观事物的抽象,类是对对象的抽象。类是一种抽象的数据类型。

population 是只有Robot有的一个属性,属于Robot类,因此为类变量;

name是整体任何事物都可以有的一个属性,是属于客观事物,因此为对象变量。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值