#!/usr/bin/python
# -*- coding: UTF-8 -*-
class People(object):
hahaname = "abc" # 公开静态名称
_hahaage = 1 # 保护静态名称
__hahasex = "难" # 私有静态名称
# 构造函数
def __init__(self, name, age, sex):
# 定义实例变量
self.name = name # 公开变量
self._sex = sex # 保护变量
self.__age = age # 私有变量
# 定义实例方法,第一个参数self
def sayHello(self):
print "sayHello"
# 定义类方法,第一个参数cls
@classmethod
def test1(cls):
print "classmethod"
# 参数可为空
@staticmethod
def test2():
print "staticmethod"
# 私有方法双下划线开头
def __test3(self):
print "__test3"
# 保护方法单下划线开头
def _test4(self):
print "_test4"
def __cmp__(self, other):
return cmp(self.name, other.name)
def __str__(self):
return "name:{},age:{},sex:{}".format(self.name, self.__age, self._sex)
class Student(People):
def __init__(self, name, age, sex, student_id):
# 调用基类函数
super(Student, self).__init__(name, age, sex)
self.__student_id = student_id
def __str__(self):
return (super(Student, self).__str__() + ",student_id:{}").format(self.__student_id)
if __name__ == '__main__':
peos = [People(name="whf", age=1, sex="男"),
People(name="oo", age=1, sex="男"),
Student(name="ada", age=1, sex="男", student_id="20136302")]
peos.sort()
for peo in peos:
print peo
Python 对象知识实践
最新推荐文章于 2024-03-18 18:56:30 发布