zoukankan      html  css  js  c++  java
  • 类与对象

    类和对象是面向对象编程的两个主要方面。创建一个新类型,而对象这个类的 实例 。这类似于你有一个int类型的变量,这存储整数的变量是int类的实例(对象)。都差不多,但是始终理解的很浅,写不出自己想要的东西来。

    这是最简单的一个类

    class person:
        pass
    p = person()
    
    print p

    我们使用class语句后跟类名,创建了一个新的类。这后面跟着一个缩进的语句块形成类体。

    我们使用类名后跟一对圆括号来创建一个对象/实例

    #!/usr/bin/python
    # Filename: objvar.py
    
    class Person:
        '''Represents a person.'''
        population = 0
    
        def __init__(self, name):
            '''Initializes the person's data.'''
            self.name = name
            print '(Initializing %s)' % self.name
    
            # When this person is created, he/she
            # adds to the population
            Person.population += 1
    
        def __del__(self):
            '''I am dying.'''
            print '%s says bye.' % self.name
    
            Person.population -= 1
    
            if Person.population == 0:
                print 'I am the last one.'
            else:
                print 'There are still %d people left.' % Person.population
    
        def sayHi(self):
            '''Greeting by the person.
    
            Really, that's all it does.'''
            print 'Hi, my name is %s.' % self.name
    
        def howMany(self):
            '''Prints the current population.'''
            if Person.population == 1:
                print 'I am the only person here.'
            else:
                print 'We have %d persons here.' % Person.population
    
    swaroop = Person('Swaroop')
    swaroop.sayHi()
    swaroop.howMany()
    
    kalam = Person('Abdul Kalam')
    kalam.sayHi()
    kalam.howMany()
    
    swaroop.sayHi()
    swaroop.howMany()

    简单的打印,定义了几个方法。其实写这个主要是逻辑要清晰,不然总是混乱不堪。基础知识快学完了。加油一波,兄弟。

  • 相关阅读:
    第四节 哈希类型
    第三节 string类型
    第二节 redis的数据类型和一些通用的键命令
    第一节 Redis的安装配置
    第三十二节 定时器
    第三十一节 sed命令
    第三十节 awk命令
    第二十九节 cut命令
    第二十八节 函数和脚本调试
    Gartner 如何看 RASP 和 WAF?
  • 原文地址:https://www.cnblogs.com/sakura3/p/8393528.html
Copyright © 2011-2022 走看看