Python 类与对象
程序员文章站
2022-04-05 19:42:30
...
类与对象是面向对象编程的两个主要方面。
#创建一个名叫 Person 的类
class Person:
def __init__(self,name):
self.name = name
def say_hi(self):#def 方法
print("my name is {}".format(self.name))
p = Person("jimmy") #给Person类创建一个对象p或实例p
p.say_hi()
(output:)my name is jimmy
- 1,2参数传递给方法.
- 3 self参数指向当前实例自身.
- 4 我们不需要传递实例自身给方法,Python解释器自己会做这些操作的.
__init__方法
__init__方法会在类的对象被实例化时(p = Person("jimmy"))立即运行。这方法可以对任何你想进行操作的目标对象进行初始化操作。
self
类方法与普通函数的区别在于多了一个self名称。当你调用功能时,Pyhton会自动为该参数赋值。
没有参数的实例方法也必须拥有一个参数——self.
继承
下面这段代码引用自《a byte of python》
class SchoolMember:
"""公用类,父类型"""
def __init__(self, name, age):
self.name = name
self.age = age
print(('Initialized SchoolMember:{}').format(self.name))
def tell(self):
"""tell me more"""
print('name:"{}" Age:"{}"'.format(self.name, self.age),end = " ")
class Teacher(SchoolMember):#子类型
"""代表一个老师"""
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age)
self.salary = salary
print('Initialized Teacher:{}'.format(self.name))
def tell(self):
SchoolMember.tell(self)
print('Salary:"{:d}"'.format(self.salary))
class Student(SchoolMember):#子类型
"""代表一个学生"""
def __init__(self, name, age, marks):
SchoolMember.__init__(self, name, age)
self.marks = marks
print('Initialized Student:{}'.format(self.name))
def tell(self):
SchoolMember.tell(self)
print('marks:"{:d}"'.format(self.marks))
if __name__ == '__main__':
t = Teacher('Mrs. Shrividya',40 ,30000)
s = Student('XiaoMing', 20, 75 )
print()
members = [t,s]
for member in members:
member.tell()
output:
Initialized SchoolMember:Mrs. Shrividya
Initialized Teacher:Mrs. Shrividya
Initialized SchoolMember:XiaoMing
Initialized Student:XiaoMing