关与python面向对象的认识

2022/9/15 14:19:28

本文主要是介绍关与python面向对象的认识,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

面向对象编程

类:从一堆对象中以抽象的方式把相同的特征归类得到。

  1. 抽象类
  2. 实列

子类抽象为父类,子类继承父类特征。
类实例化为实例,实例抽象为类。

    class Human(object):

        century = 21

        def __init__(self, name, age):
            self.name = name
            self.age = age
            print("init work")

        def speak(self, language):
            print('%s has speak %s ability'% (self.name, language))

        def write(self, word):
            print('%s has write %s ability'% (self.name, word))

        def walk(self):
            print('%s has walk ability'% self)
    Allen = Human('Allen-Cart', 16) # 输出结果:init work
    print(Allen.name, Allen.age) # 输出结果:Allen-Cart 16

    print(Allen.speak,Allen.write,Allen.walk)
    # <bound method Human.speak of <__main__.Human object at 0x10ab50160>>
    # <bound method Human.write of <__main__.Human object at 0x10ab50160>>
    # <bound method Human.walk of <__main__.Human object at 0x10ab50160>>

    print(Human.speak,Human.write,Human.walk)
    # <function Human.speak at 0x110ba5378>
    # <function Human.write at 0x110ba5400>
    # <function Human.walk at 0x110ba5488>

    Allen.speak("Chinese") # Allen-Cart has speak Chinese ability
    Allen.write("Chinese") # Allen-Cart has write Chinese ability
    Allen.walk() # <__main__.Human object at 0x10ab50160> has walk ability.

    Human.walk('James') # James has walk ability


这篇关于关与python面向对象的认识的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程