• Python之面向对象编程


    一、面向对象

    面对对象,对象中的数据和具体实现过程,可以不用看到。

    面对对象最重要的是“类”和“实例”,

    类:创建实例的模板,“实例:是一个具体的对象

    1.1 类

         类变量可以直接访问(例如:person.name)

         类函数不能直接访问,必须要给函数加@classmethod,变成类函数,才可以直接调用,类函数的第一个参数是cls。

         (例如:person.play())

    class person:
        name='default'#类变量
        age=0
        gender='male'
        weight=0
        def set_name(self,name):#类方法
            self.name=name#函数的参数赋给实例的变量
    
        def eat(self):
            print("eating")
    
        def play(self):
            print("playing")
    
        def jump(self):
            print("jumping")
    --------------------------------
    print(person.name)#类变量可以直接访问
    打印结果:
    default
    --------------------------------------------------------
    person.play()#类变量不能直接访问,需要加@classmethod,变成类函数,才能直接访问
    打印结果:
       person.play()#
    TypeError: play() missing 1 required positional argument: 'self'
    第二段代码:给类函数加@classmethd,变成类函数,可以直接访问
    class person:
        name='default'#类变量
        age=0
        gender='male'
        weight=0
        def set_name(self,name):#类方法
            self.name=name#函数的参数赋给实例的变量
    
        def eat(self):
            print("eating")
        @classmethod
        def play(self):
            print("playing")
    
        def jump(self):
            print("jumping")
    -------------------------------------------
    person.play()
    打印结果:
    playing

    1.2 实例

    类是一个模板,创建类时,可以将类必须有的属性初始化进去。然后每个实例都有这些属性,但具体属性的值可以不同。

    class person:
        # 实例化函数,第一个参数永远是self,指向实例本身
        #创建实例时,必须传入于__init__匹配的参数
        def __init__(self,name,age,score):
            self.name=name#将参数要赋值给实例的变量
            self.age=age
            self.score=score
    
        def eat(self):
            print(f"{self.name} is eating")
    
        @classmethod
        def play(self):
            print("playing")
    
        def jump(self):
            print("jumping")
    
        def get_score(self):
            if self.score>=90:
                return "A"
            elif self.score>=60:
                return "B"
            else:
                return "C"
    --------------------------------------------------------------
    lyh=person("balllyh",25,96)#实例化
    lyh.eat()#实例函数可以直接调用
    print(lyh.name)
    print(lyh.get_score())
    打印结果:
    balllyh is eating
    balllyh
    A
  • 相关阅读:
    如何在WinPE下安装xp安装版
    好用、功能强大的JQuery弹出层插件
    设计模式-旧话重提之类工厂的使用
    How can I manage Internet Explorer Security Zones via the registry?
    设计模式行为模式Behavioral Patterns()之FlexibleService模式
    how to design a new tree view control
    在C#中通过webdav操作exchange
    Yahoo! User Interface Library (哈偶然发现了这个东西)
    设计模式[2]旧话重提之工厂模式
    const和static readonly 的区别
  • 原文地址:https://www.cnblogs.com/balllyh/p/15716888.html
Copyright © 2020-2023  润新知