在Python中访问实例变量的不同方法
实例属性是那些不被对象共享的属性。每个对象都有自己的实例属性副本,即对于每个对象,实例属性都不同。
访问类的实例变量有两种方式:
- 在类内使用自我和对象引用。
- 使用
getattr()
方法
示例 1:使用 Self 和对象引用
#creating class
class student:
# constructor
def __init__(self, name, rollno):
# instance variable
self.name = name
self.rollno = rollno
def display(self):
# using self to access
# variable inside class
print("hello my name is:", self.name)
print("my roll number is:", self.rollno)
# Driver Code
# object created
s = student('HARRY', 1001)
# function call through object
s.display()
# accessing variable from
# outside the class
print(s.name)
输出:
hello my name is: HARRY
my roll number is: 1001
HARRY
示例 2:使用 getattr()
# Python code for accessing attributes of class
class emp:
name='Harsh'
salary='25000'
def show(self):
print(self.name)
print(self.salary)
# Driver Code
e1 = emp()
# Use getattr instead of e1.name
print(getattr(e1,'name'))
# returns true if object has attribute
print(hasattr(e1,'name'))
# sets an attribute
setattr(e1,'height',152)
# returns the value of attribute name height
print(getattr(e1,'height'))
# delete the attribute
delattr(emp,'salary')
输出:
Harsh
True
152