• python添加、修改、删除、访问类对象属性的2种方法


    1.直接添加、修改、删除、访问类对象属性

    class Employee (object):

      empCount = 0

     

      def __init__(self, name, salary) :

        self.name  = name

        self.salary = salary

        Employee.empCount += 1

     

      def displayCount(self) :    

        print "total employee ",Employee.empCount

     

      def displayEmployee(self) :

        print "name :",self.name  , ", salary :", self.salary

     

    emp1 = Employee("SR", 10000)

    emp1.displayCount()

    emp1.displayEmployee()

    emp1.salary = 20000  

    print emp1.salary

    emp1.age = 25  

    print emp1.age

    del emp1.age

     

    Employee.empCount=500

    print Employee.empCount

     

    Employee.cc="abc"

    print Employee.cc

     

    del Employee.empCount

    print Employee.empCount

     

     

    2.使用函数添加、删除、修改、访问类对象属性

    class Employee(object):

        empCount=0

     

        def __init__(self,name,salary):

            self.name=name

            self.salary=salary

            Employee.empCount+=1

     

        def  displayCount(self):

            print "total employee ",Employee.empCount

     

        def displayEmployee(self):

            print "name:",self.name,",salary:",self.salary

     

    emp1=Employee("SR",100000)

    if hasattr(emp1,"name"):

        print u"属性name存在"

    else:

        print u"属性name不存在"

       

    try:

        a=getattr(emp1,"name")

        print u"name属性的值:",a

    except Exception,e:

        print e

     

    setattr(emp1,"tel","13111111111")

    try:

        a=getattr(emp1,"tel")

        print u"新添加的tel属性的值:",a

    except Exception,e:

        print e

     

    try:

        delattr(emp1,"tel")

    except Exception,e:

        print e

    else:

        if hasattr(emp1,"tel"):

            print u"属性tel存在"

        else:

            print u"属性tel不存在"

     

  • 相关阅读:
    6.简易计算器
    5.用户密码管理
    4.方法重载
    3.对象数组做参数
    2.迷你DVD管理系统
    1.二维数组计算班级成绩
    31.向数组中插入一个元素
    30.使用Arrays类的各种方法
    Java开发中的23种设计模式详解(转)
    个人代码归档
  • 原文地址:https://www.cnblogs.com/reyinever/p/8627833.html
Copyright © 2020-2023  润新知