使用type()判断对象类型
type(123)
<class ‘int’>type(123)==int
True
使用isinstance()判断class的类型
继承关系是:object -> Animal -> Dog -> Husky
a = Animal()
d = Dog()
h = Husky()
isinstance(h, Husky)
Trueisinstance(h, Husky)
Trueisinstance(h, Animal)
True
self.name 在类外部可以访问;
self.__age 只能在类内部可以访问,类外包无法访问。
class person(object):
def __init__(self,name,age):
self.name=name
self.__age=age
def run(self):
print(self.name+' is running.')
def getAge(self):
return self.__age
def setAge(self,age):
self.__age=age
a=person('Bao',19)
a.run()
a.setAge(36)
print(a.name)
print(a.getAge())
使用类中的全局变量: 类.变量名, 如 Student.count
class Student(object):
count = 0
def __init__(self, name):
Student.count=Student.count +1
self.name = name
方法twice通过传入类
class Animal(object):
def run(self):
print('animal is running.')
class Dog(Animal):
def run(self):
print('Dog is running.')
class Cat(Animal):
def __init__(self,name):
self.name=name
def twice(Animal):
Animal.run()
Animal.run()
a=Animal()
d=Dog()
c=Cat('CC')
twice(d)
使用dir查看一个对象的所有属性和方法
dir(c)
输出:['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name', 'run']
getattr()、setattr()以及hasattr()
print(hasattr(c,'name'))
print(getattr(c,'name'))
setattr(c,'name','DD')
print(getattr(c,'name'))
输出:
True
CC
DD
使用@property、@***.setter 对参数进行检查
class tree(object):
@property
def height(self):
return self._height
@height.setter
def height(self,value):
if not isinstance(value,int):
raise ValueError('not int')
self._height=value
t=tree()
t.height=65
print(t.height)