python_的面向对象编程

时间:2021-04-17 06:05:30

废话不多说,先弄个对象来看看

class Student(object):

    def __init__(self, name, score):
self.name = name
self.score = score def print_score(self):
print('name: %s score : %s' %(self.name, self.score)) #赋值
shb = Student('shb', 99)
#调用对象的方法
shb.print_score() 打印:
name: shb score : 99

私有属性,在属性名称前加上2个下划线__,只有内部可以访问,外部不能访问;

#面向对象编程
class Student(object): def __init__(self, name, score):
self.__name = name
self.score = score def print_score(self):
print('name: %s score : %s' %(self.__name, self.score)) #赋值
shb = Student('shb', 99)
#调用对象的方法
shb._name
打印:
AttributeError: 'Student' object has no attribute '_name'

那如果变量变成私有的了,如何访问和设置类中的属性呢 - 通过set  和 get 方法

#面向对象编程
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score def set_score(self, score):
self.__score = score def set_name(self, name):
self.__name = name def get_name(self):
return self.__name def get_score(self):
return self.__score def print_score(self):
print('name: %s score : %s' %(self.__name, self.__score)) #赋值
shb = Student('shb', 27)
#重新设置score值
shb.set_score(299)
print(shb.get_name(), shb.get_score())
打印:
shb 299

获取对象属性的类型函数:   type()

获取对象的所有属性的类型函数:   type()

#面向对象编程
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score def set_score(self, score):
self.__score = score def set_name(self, name):
self.__name = name def get_name(self):
return self.__name def get_score(self):
return self.__score def print_score(self):
print('name: %s score : %s' %(self.__name, self.__score)) #赋值
shb = Student('shb', 27)
#重新设置score值
shb.set_score(299)
print(shb.get_name(), shb.get_score(), type(shb.get_score()),'\n', dir(shb))
打印:
#面向对象编程
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score def set_score(self, score):
self.__score = score def set_name(self, name):
self.__name = name def get_name(self):
return self.__name def get_score(self):
return self.__score def print_score(self):
print('name: %s score : %s' %(self.__name, self.__score)) #赋值
shb = Student('shb', 27)
#重新设置score值
shb.set_score(299)
print(shb.get_name(), shb.get_score(), type(shb.get_score()),'\n', dir(shb))