• python 四种方法修改类变量,实例对象调用类方法改变类属性的值,类对象调用类方法改变类属性的值,调用实例方法改变类属性的值,直接修改类属性的值


    三种方法修改类变量,实例对象调用类方法改变类属性的值,类对象调用类方法改变类属性的值,调用实例方法改变类属性的值,类名就是类对象,city就是类变量,

    #coding=utf-8

    class employee(object) :

      city = 'BJ' #类属性

      def __init__(self, name) :

        self.name = name #实例变量

      #定义类方法

      @classmethod

      def getCity(cls) :

        return cls.city

      #定义类方法

      @classmethod

      def setCity(cls, city) :

        cls.city = city

      #实例方法

      def set_City(self, city) :

        employee.city = city

    emp = employee('joy') #创建类的实例

    print emp.getCity() #通过实例对象引用类方法

    print employee.getCity()#通过类对象引用类方法

    emp.setCity('TJ')#实例对象调用类方法改变类属性的值

    print emp.getCity()

    print employee.getCity()

               

    employee.setCity('CD')#类对象调用类方法改变类属性的值

    print emp.getCity()

    print employee.getCity()

    emp.set_City('SH')#调用实例方法改变类属性的值

    print emp.getCity()

    print employee.getCity()

    employee.city = 20 #直接修改类属性的值

    print emp.getCity()

    print employee.getCity()

     

    c:Python27Scripts>python task_test.py

    BJ

    BJ

    TJ

    TJ

    CD

    CD

    SH

    SH

    20

    20

  • 相关阅读:
    尽可能装满的背包问题
    mysql的下载与安装
    IDEA中安装ibatis插件
    tomcat启动失败,提示信息:Unable to ping server at localhost:1099
    http响应头
    查看电脑的IP地址及配置
    IDEA中不同项目配置不同JDK
    Navicat for mysql的下载及破解
    java中String的equals()和 ==
    BeanUtils出现Java.lang.NoClassDefFoundError解决
  • 原文地址:https://www.cnblogs.com/xiaxiaoxu/p/8961106.html
Copyright © 2020-2023  润新知