class Student(object):
def __init__(self, name, gender):
self.__name = name
self.__gender = gender
def set_gender(self, gender):
if gender == 'male':
self.__gender = gender
elif gender == 'female':
self.__gender = gender
else:
pass
def get_gender(self):
return self.__gender
# 测试:
bart = Student('Bart', 'male')
if bart.get_gender() != 'male':
print('测试失败!')
else:
bart.set_gender('female')
if bart.get_gender() != 'female':
print('测试失败!')
else:
print('测试成功!')
#下面的操作会导致实例增加一个新变量 变量名为__name
>>> bart.__name = 'New Name' # 设置__name变量!
>>> bart.__name
'New Name'
class类
class关键字,继承了object 表示了一个student类的定义
一般定义__xxx为私有变量, 而python解释器会自动将私有变量名重新命名,避免外界的直接引用;
例如:__name
变量改成了_Student__name
类中私有对象的访问应该通过get() 和 set() 函数进行;
继承与多态
class Animal(object):
def run(self):
print('Animal is running...')
#继承Animal
class Dog(Animal):
#覆盖父类的函数run()
def run(self):
print('Dog is running...')
#拓展子类的新功能
def eat(self):
print('Eating meat...')
def run_twice(animal):
animal.run()
animal.run()
class Tortoise(Animal):
def run(self):
print('Tortoise is running slowly...')
>>> run_twice(Tortoise())
Tortoise is running slowly...
Tortoise is running slowly...
当我们调用run_twice函数的时候,只要对象有run方法都可以顺利运行!一个函数可以适用多样性的类,无论是父类还是子类
isinstance
用来查询变量是否属于某一类型比如,str, int 或者类
>>> isinstance('a', str)
True
>>> isinstance(123, int)
True
>>> isinstance(b'a', bytes)
True
>>> isinstance([1, 2, 3], (list, tuple))
True
>>> isinstance((1, 2, 3), (list, tuple))
True
>>> dir('ABC')
['__add__', '__class__',..., '__subclasshook__', 'capitalize', 'casefold',..., 'zfill']
dir()
可以获取对象的所有属性和方法;
getattr()
、setattr()
以及hasattr()
,我们可以直接操作一个对象的状态
>>> class MyObject(object):
... def __init__(self):
... self.x = 9
... def power(self):
... return self.x * self.x
...
>>> obj = MyObject()
>>> hasattr(obj, 'x') # 有属性'x'吗?
True
>>> obj.x
9
>>> hasattr(obj, 'y') # 有属性'y'吗?
False
>>> setattr(obj, 'y', 19) # 设置一个属性'y'
>>> hasattr(obj, 'y') # 有属性'y'吗?
True
>>> getattr(obj, 'y') # 获取属性'y'
19
>>> obj.y # 获取属性'y'
19
>>> getattr(obj, 'z', 404) # 获取属性'z',如果不存在,返回默认值404
404
>>> fn = getattr(obj, 'power') # 获取属性'power'并赋值到变量fn
>>> fn # fn指向obj.power
<bound method MyObject.power of <__main__.MyObject object at 0x10077a6a0>>
>>> fn() # 调用fn()与调用obj.power()是一样的
81
getattr()
、setattr()
以及hasattr()也可以用在方法上
类的属性不需要实例化就可以直接访问,并且可以被所有实例访问
class Student(object):
count = 0
def __init__(self, name):
self.__name = name
Student.count = Student.count + 1
# 测试:
if Student.count != 0:
print('测试失败!')
else:
bart = Student('Bart')
if Student.count != 1:
print('测试失败!')
else:
lisa = Student('Bart')
if Student.count != 2:
print('测试失败!')
else:
print('Students:', Student.count)
print('测试通过!')
参考来源:https://www.liaoxuefeng.com/wiki/1016959663602400/1017497232674368