zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    HashMap
    java反射
    arraylist和linkedlist区别
    int和Integer的区别
    java 数组排序并去重
    矩阵链乘法问题
    找零问题
    硬币收集问题
    最大借书量问题
    钢条切割问题
  • 原文地址:https://www.cnblogs.com/xiaxiaoxu/p/8961106.html
Copyright © 2011-2022 走看看