内置类属性
内置类属性:python中每个类都拥有内置的类属性
- _name_
- _doc_
- _dict_
- _module_
- _bases_
代码实例
class Cat:
猫类
number = 0
def __init__(self, name='', color='white'):
self.name = name
self.color = color
def run(self):
print(self.name, 'is running')
@staticmethod
def miao():
print('miao')
@classmethod
def getNumber(cls):
print('number:', cls.number)
1.name
获取类的名字(str)
print(Cat.__name__)
print(Cat.__name__)
cat1 = Cat('小白')
2.类.doc
获取类的说明文档
print(Cat.__doc__)
3.类.dict
对象.dict
获取所有属性和对应的值转换成字典
print(cat1.__dict__)
print(Cat.__dict__)
4.类.module
获取当前类所在的模块的名字
print(Cat.__module__)
5.类.bases
获取当前类的父类(元组,因为可以多继承)
print(Cat.__bases__)
私有化
- python中类中的属性和方法的私有化:直接在属性名或者方法名前加上(命名以''开头)
- 属性或者方法私有:在外部不能直接使用,可以在类的内部使用
import random
class Person:
'''人类'''
__number = 1 # 私有类字段
def __init__(self, name='', age=0):
self.name = name
self.__age = age
def showAge(self):
print(self.__age - 10)
self.__run()
@classmethod
def __showNum(cls):
print(cls.__number)
@staticmethod
def __aaao(cls):
print('static')
cls.__showNum()
def showAll(self, cls):
Person.__aaao(Person)
# 私有的对象方法,只能在内部调用
def __run(self):
print('%s is running' % self.name)
class Student:
def __init__(self, name):
self.name = name
self.study_id = ''
def __creat_id(self):
return 'py1805' + str(random.randint(1, 50)).rjust(3, '0')
def creat(self, name):
stu = Student(name)
stu.study_id = self.__creat_id()
return stu
if __name__ == '__main__':
p1 = Person('z3', 30)
# print(p1.__age)
# print(p1.__run())
p1.showAge()
p1.showAll(Person)
# 私有化原理:在方法和属性前加上_类名
print(Person._Person__number)
getter和setter
- 属性假私有化:声明对象属性的时候,在属性名前面加一个'_',来告诉别人这个属性不可以使用.要通过getter和setter来获取属性值和修改属性值
1.getter:获取属性值
@property
def 属性名(去掉下划线)(self):
return 返回值
- 如果获取对象的某个属性前需要处理数据,就添加getter
2.setter:给属性赋值
- 一个属性必须要有getter,才能添加setter
@getter名.setter
def getter名(self,参数):
self._getter名 = 参数
- 如果给对象赋值前需要处理数据,添加setter
class Student:
'''学生类'''
def __init__(self):
# 声明属性前面加一个'_'是为了告诉别人这个属性不能直接使用
self._name = ''
self._score = 0
self._age = 0
# 给属性_name添加getter
@property
def name(self):
return self._name
# 给属性_name添加setter
@name.setter
def name(self, name):
self._name = name
@property
def score(self):
return self._score
@score.setter
def score(self, score):
self._score = score
@property
def age(self):
return str(self._age) + '岁'
@age.setter
def age(self, age):
if 0 <= age <= 120:
self._age = age
return
print('非法输入')
if __name__ == '__main__':
stu1 = Student()
stu1.score = 20
stu1.age = 999
print(stu1.age)
print(stu1.score)
练习
import json
class Data(object):
def __init__(self,
type='',
text='',
user_id='',
name='',
screen_name='',
width=0,
height=0,
themes=''):
self.type = type
self.text = text
self.user_id = user_id
self.name = name
self.screen_name = screen_name
self._width = width
self._height = height
self._themes = themes
@property
def width(self):
return self._width
@width.setter
def width(self, width):
self._width = int(width)
@property
def height(self):
return self._height
@height.setter
def height(self, height):
self._height = int(height)
@property
def themes(self):
if not self._themes:
return '无'
@themes.setter
def themes(self, themes):
self._themes = themes
def main():
filePath = './day13-面向对象(进阶)/data.json'
datas = []
with open(filePath, encoding='utf-8') as f:
data = json.load(f)
for i in data['data']:
j = Data()
j.type = i['type']
j.text = i['text']
j.user_id = i['user_id']
j.name = i['name']
j.screen_name = i['screen_name']
j.width = i['width']
j.height = i['height']
j.themes = i['themes']
datas.append(j)
for i in datas:
print(i.__dict__)
print('-0-0-0-0-0-0-0-0-0-0-0-0')
with open('./day13-面向对象(进阶)/datas.json', 'w') as f1:
datas[0] = datas[0].__dict__
datas[1] = datas[1].__dict__
json.dump(datas, f1)
if __name__ == '__main__':
main()
类的继承
- 子类:继承者
- 父类(超类):被继承者
1. 集成基础
- python中类是可以继承的,并且支持多继承
class 类名(父类列表):
"""类的说明"""
属性
方法
说明:所有类默认继承基类object
2.能继承哪些内容
继承:直接拥有父类的属性和方法(继承后父类的属性和方法还是存在)
- a.对象的属性和方法,类的字段和类方法,静态方法都可以继承(私有的继承无意义)
- b.slots的约束不会被继承
class Person:
'''人类'''
number = 666
def __init__(self):
self.name = ''
self.age = 0
self.gender = '男'
def eat(self):
print('%s在吃饭' % self.name)
@classmethod
def getNum(cls):
return cls.number
@staticmethod
def destory():
return print('aaaaa')
class Student(Person):
'''学生类'''
if __name__ == '__main__':
stu = Student()
stu.name = '猪小明'
print(stu.name, stu.age, stu.eat(), Student.number, Student.destory())
网友评论