定义类:
-----------------------------------------------------------------------------------
class People:
#类属性,所有示例共有
name=None
age=None
company="Alibaba"
def __init__(self, input_name, input_age):
self.name=input_name
self.age=input_age
def printName_Age(self):
print("My name is "+self.name+", "+"and my age is"+str(self.age)+".")
def printCompany(self):
print("Come from", People.company)
def printTotal(self):
print("Method call in class:")
People.printName_Age(self)
People.printCompany(self)
-----------------------------------------------------------------------------------------------
实例化:
------------------------------------------------------------------------------------------------
people = People('风清扬', 50)
people.printName_Age()
people.printCompany()
people.printTotal()
其中People类的printTotal()函数有两种实现方法
1、格式:类名.方法名(self),注意:方法名内必须传入一个实例对象的指针,self后可根据方法定义放入适当实参
2、格式:self.方法名(方法列表),注意:方法列表不应该包括self
本文详细介绍了Python中类的定义与使用,包括类属性、实例属性、构造方法、实例方法等核心概念。通过实例演示了如何创建类和实例化对象,以及调用类的方法。


被折叠的 条评论
为什么被折叠?



