Power | | Of course, sometimes we need to obtain relevant information about the class. We can use the following methods:
type(obj): to obtain the corresponding type of the object;
isinstance(obj, type ): Determine whether the object is an instance of the specified type;
hasattr(obj, attr): Determine whether the object has the specified attributes/methods;
getattr(obj, attr[, default] ) Get the value of the attribute/method. If there is no corresponding attribute, the default value is returned (provided that default is set), otherwise an AttributeError exception will be thrown;
setattr(obj, attr, value): Set the The value of the attribute/method, similar to obj.attr=value;
dir(obj): You can get a list of all attributes and method names of the corresponding object:
2. Method Access control
In fact, we can also regard methods as attributes of the class. Then the access control of methods is the same as attributes, and there is no actual private method. Everything relies on programmers to consciously abide by Python programming standards.
The example is as follows, the specific rules are the same as the attributes,
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class User(object):
def upgrade(self):
pass
def _buy_equipment(self):
pass
def __pk(self):
pass
3. Method decorator
@classmethod uses the class directly when calling Name class call, not an object
@property You can call the method just like accessing properties
See the example for specific usage:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class UserInfo(object):
lv = 5
def __init__(self, name, age, account):
self.name = name
self._age = age
self.__account = account
def get_account(self):
return self.__account
@classmethod
def get_name(cls):
return cls.lv
@property
def get_age(self):
return self._age
if __name__ == '__main__':
userInfo = UserInfo('两点水', 23, 347073565);
# 打印所有属性
print(dir(userInfo))
# 打印构造函数中的属性
print(userInfo.__dict__)
# 直接使用类名类调用,而不是某个对象
print(UserInfo.lv)
# 像访问属性一样调用方法(注意看get_age是没有括号的)
print(userInfo.get_age)
The result of running:
Next Section