终于学到PYTHON的类啦~~

简介:

#!/usr/bin/python
# Filename:objvar.py

class Robot:
    '''Represents a robot,with a name.'''

    population = 0

    def __init__(self,name):
        '''Iinitializes the data.'''
        self.name = name
        print('(Initialize {0})'.format(self.name))

        Robot.population += 1

    def __del__(self):
        '''I am dying'''
        print('{0} is being destroyed!'.format(self.name))

        Robot.population -= 1

        if Robot.population == 0:
            print('{0} was the last one.'.format(self.name))
        else:
            print('There are still {0:d} robots working.'.format(Robot.population))

    def sayHi(self):
        '''Greeting by the robot.

     
        Yeah,they can do that.'''
        print('Greetings, my master call me{0}.'.format(self.name))

    def howMany():
        '''Print the current population.'''
        print('We have {0:d} robots.'.format(Robot.population))
    howMany = staticmethod(howMany)

droid1 = Robot('R2-D2')
droid1.sayHi()
Robot.howMany()

droid2 = Robot('C-3P0')
droid2.sayHi()
Robot.howMany()

print('\nRobots can do some work here.\n')

print("Robots have finished their work. So let's destroy them.")

del droid1
del droid2

Robot.howMany()

目录
相关文章
|
1月前
|
安全 Python
在Python中导入类
在Python中导入类
21 1
|
2天前
|
Python
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
22 0
|
2天前
|
索引 Python
python 格式化、set类型和class类基础知识练习(上)
python 格式化、set类型和class类基础知识练习
21 0
|
3天前
|
Python
python学习12-类对象和实例对象
python学习12-类对象和实例对象
|
24天前
|
Python
Python类(class)中self的理解
Python类(class)中self的理解
17 0
|
25天前
|
Python
Python类与对象:深入解析与应用
本文介绍了Python中的核心概念——类和对象,以及它们在面向对象编程中的应用。类是用户定义的类型,描述具有相同属性和行为的对象集合;对象是类的实例,具备类的属性和方法。文章通过示例讲解了如何定义类、创建及使用对象,包括`__init__`方法、属性访问和方法调用。此外,还阐述了类的继承,允许子类继承父类的属性和方法并进行扩展。掌握这些概念有助于提升Python编程的效率和灵活性。
|
1月前
|
机器学习/深度学习 设计模式 开发者
python类用法(四)
python类用法(四)
17 0
|
1月前
|
Python
python类用法(三)
python类用法(三)
16 0
|
1月前
|
Python
python类用法(二)
python类用法(二)
17 0
|
1月前
|
存储 Java 数据安全/隐私保护
python类用法(一)
python类用法(一)
20 0

热门文章

最新文章