class Test:
def prt(self):
print(self) #self代表的是类的实例,代表当前的对象的地址
print(self.__class__) #self.__class_则指向类
t = Test()
t.prt()
1. Create an instance object
class Employee:
'所有员工的基类'
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)
emp1=Employee('Zara',2000)
emp2=Employee('Manni',5000)
emp1.displayEmployee()
emp2.displayEmployee()
print("Total Employee %d" % Employee.empCount)
You can add, delete, and modify the properties of the class.
The following functions can access attributes:
- getattr(obj, name[, default]): Access the attributes of the object.
- hasattr(obj,name): Check whether an attribute exists.
- setattr(obj,name,value): Set an attribute. If the attribute does not exist, a new attribute will be created.
- delattr(obj, name): delete attribute.
class Employee:
'所有员工的基类'
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)
emp1=Employee('Zara',2000)
emp2=Employee('Manni',5000)
emp1.displayEmployee()
emp2.displayEmployee()
print("Total Employee %d" % Employee.empCount)
emp1.age=7 #添加属性
print(emp1.age)
emp1.age=8 #修改属性
print(emp1.age)
print(hasattr(emp1,'age')) #判断empt1中是否有age这个属性
print(getattr(emp1,'age')) #返回属性的值
setattr(emp1,'age',10) #添加属性
print(getattr(emp1,'age')) #返回属性的值
delattr(emp1,'age') #删除属性
print(getattr(emp1,'age')) #age不存在
3.Python built-in class attributes
- __dict__: the attributes of the class (contains a dictionary, composed of the data attributes of the class)
- __doc__: the docstring of the class
- __name__: class name
- __module__: The module where the class definition is located (the full name of the class is'__main__.className', if the class is located in an imported module mymod, then className.__module__ is equal to mymod)
- __bases__: all parent elements of the class (contains a tuple consisting of all parent classes)
class Employee:
'所有员工的基类'
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)
print("Employee.__doc__:", Employee.__doc__)
print("Employee.__name__:", Employee.__name__)
print("Employee.__module__:", Employee.__module__)
print("Employee.__bases__:", Employee.__bases__)
print("Employee.__dict__:", Employee.__dict__)