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()

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

  • 相关阅读:
    104每日博客
    924每日博客
    921每日博客
    928每日博客
    929每日博客
    930每日博客
    927每日博客
    大志非才不就,大才非学不成—我的博文资源汇总
    vue 项目搭建
    Vant 使用记录
  • 原文地址:https://www.cnblogs.com/sakura3/p/8393528.html
Copyright © 2011-2022 走看看