创建一个类
class Person:
'类的文档字符串'
count = 0
def __init__(self,name,age):
self.name = name
self.age = age
Person.count +=1
def displaycount(self):
print("total person %d" % Person.count)
def myfunc(self):
print("Name: " + str(self.name) + " Age: "+ str(self.age))
创建实例对象
p1 = Person("test01",21)
p2 = Person("test02",22)
调用类方法
p1.myfunc()
p2.myfunc()
print("total person %d" % Person.count)
输出:
Name: test01 Age: 21
Name: test02 Age: 22
total person 2
修改类的属性
p1.age = 100
p1.Salary = 100000
p1.myfunc()
p2.myfunc()
输出:
Name: test01 Age: 100
Name: test02 Age: 22
hasattr():检查是否存在属性,如果存在,返回True
result = hasattr(p1,'lala')
print(result)
输出:
False
getattr():访问对象的属性,返回属性值
getresult = getattr(p1,'age')
print(getresult)
输出
21
setattr():设置一个属性,如果属性不存在,会创建一个新属性
setresult = setattr(p1,'heihei',100000)
print(p1.heihei)
输出
100000
delattr():删除属性
delresult = delattr(p1,'heihei')
print(hasattr(p1,'heihei'))
输出:
delresult = delattr(p1,'heihei')
AttributeError: heihei
因为此属性已被删除,不存在了,所以报错
内置类属性
类的文档字符串
print('Person.__doc__:',Person.__doc__)
输出
Person.__doc__: 类的文档字符串
类的属性
print('Person.__dict__:',Person.__dict__)
输出
Person.__dict__: {'__module__': '__main__', '__doc__': '类的文档字符串', 'count': 2, '__init__': <function Person.__init__ at 0x000002B18202DE18>, 'displaycount': <function Person.displaycount at 0x000002B18202DEA0>, 'myfunc': <function Person.myfunc at 0x000002B18202DF28>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>}
类名
print('Person.__name__:',Person.__name__)
输出
Person.__name__: Person
类定义所在的模块
print('Person.__module__:',Person.__module__)
输出
Person.__module__: __main__