关与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

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/289463.html

(0)
上一篇 2022年9月14日
下一篇 2022年9月14日

相关推荐

发表回复

登录后才能评论