python实例经验_在Python中创建实例对象

要创建类的实例,请使用类名称调用该类,然后传递其__init__方法接受的任何参数。"This would create first object of Employee class"

emp1 = Employee("Zara", 2000)

"This would create second object of Employee class"

emp2 = Employee("Manni", 5000)

您可以使用带点运算符和对象来访问对象的属性。将使用类名称访问类变量,如下所示:emp1.displayEmployee()

emp2.displayEmployee()

print "Total Employee %d" % Employee.empCount

示例

现在,将所有概念放在一起-#!/usr/bin/python

class Employee:

'Common base class for all employees'

empCount = 0

def __init__(self, name, salary):

self.name = name

self.salary = salary

Employee.empCount += 1

def displayCount(self):

print "Total Employee %d" % Employee.empCount

def displayEmployee(self):

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

"This would create first object of Employee class"

emp1 = Employee("Zara", 2000)

"This would create second object of Employee class"

emp2 = Employee("Manni", 5000)

emp1.displayEmployee()

emp2.displayEmployee()

print "Total Employee %d" % Employee.empCount

输出结果

执行以上代码后,将产生以下结果-Name : Zara ,Salary: 2000

Name : Manni ,Salary: 5000

Total Employee 2

您可以随时添加,删除或修改类和对象的属性-emp1.age = 7 # Add an 'age' attribute.

emp1.age = 8 # Modify 'age' attribute.

del emp1.age # Delete 'age' attribute.

可以使用以下功能代替使用普通语句访问属性:GETATTR(OBJ,名称[,默认]) -访问对象的属性。

该hasattr(OBJ,名) -检查一个属性存在与否。

该SETATTR(OBJ,名称,值) -设置属性。如果属性不存在,则将创建它。

该delattr(OBJ,名) -删除一个属性。hasattr(emp1, 'age') # Returns true if 'age' attribute exists

getattr(emp1, 'age') # Returns value of 'age' attribute

setattr(emp1, 'age', 8) # Set attribute 'age' at 8

delattr(empl, 'age') # Delete attribute 'age'

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值