目录
方法:
方法是与类相关的函数,类方法的定义与普通的函数一致。
在一般情况下,类方法的第一个参数一般为self,这种方法称为对象实例方法。
实例方法演示:
class Person4:
def say(self,name):
self.name=name
print("my name",self.name)
p=Person4()
p.say('A')
1.静态方法:
Python也允许声明与类的对象实例无关的方法,称之为静态方法。静态方法不对特定实例进行操作,在静态方法中访问对象实例会导致错误。静态方法通过装饰器@staticmethod来定义。
静态方法一般通过类名来访问,也可以通过对象实例来调用。
示例:摄氏温度与华氏温度之间的转换。
class TerperatureChange:
@staticmethod
def c2f(t_c):
t_c=float(t_c)
t_f=(t_c*9/5)+32
return t_f
@staticmethod
def f2c(t_f):
t_f = float(t_f)
t_c=(t_f-32)*5/9
return t_c
print("1.摄氏到华式")
print("2.华氏到摄氏")
choice= int(input("选择转换方式:"))
if choice == 1:
t_c=float(input("请输入摄氏温度:"))
t_f=TerperatureChange.c2f(t_c)
print("华氏温度为:",t_f)
elif choice == 2:
t_f=float(input("请输入华氏温度:"))
t_c=TerperatureChange.f2c(t_f)
print("摄氏温度为:", t_c)
else:
print("错误选择")
2.类方法
Python也允许声明属于类本身的方法,即类方法。类方法不对特定实例进行操作,在类方法中访问对象实例属性会导致错误。类方法通过装饰器@classmethod来定义,第一个形式参数必须为类对象本身,通常为cls。
类方法一般通过类名来访问,也可以通过对象实例来调用
类方法第一个参数为cls,但调用时用户不能给该参数传值。Python自动把类对象传递给该参数.调用子类继承父类的类方法时传入的cls是子类对象,而非父类对象。
类方法示例:
class Foo:
classname ="Foo"
def __init__(self,name):
self.name =name
def f1(self):
print(self.name)
@staticmethod
def f2():
print("static")
@classmethod
def f3(cls):
print(cls.classname)
f=Foo("1")
f.f1()
Foo.f2()
Foo.f3
3.__init__()和__new__()方法
__init__()方法即构造函数,用于执行类的实例的初始化工作。创建完对象后调用,初始化当前对象,无返回值。
__new__()是一个类方法,在创建对象时调用,返回当前对象的一个实例,一般无需重载该方法。
__init__()方法示例:
class Person5:
def __init__(self,name):
self.name=name
def say(self):
print('Hi,my name is',self.name)
p=Person5('Alex')
p.say()
__new__()方法示例:
class Person:
count=0
def __init__(self,name,age):
self.name=name
self.age=age
Person.count+=1
def __del__(self):
Person.count-=1
def say(self):
print('my name is',self.name)
def get_count():
print('count is ',Person.count)
print("总计数为:",Person.count)
p1=Person('alex',25)
p1.say()
Person.get_count()
p2=Person("broky",28)
p2.say()
Person.get_count()
del p1
Person.get_count()
del p2
Person.get_count()
4.私有方法和公有方法
与私有属性类似,Python约定以两个下划线开头,但不以两个下划线结束的方法是私有的,其他为公共的。以双下划线开始和结束的方法是Python专有的特殊方法。同样不能直接访问私有方法,要在其他方法中访问
class Book:
def __init__(self,name,author,price):
self.name = name
self.author = author
self.price = price
def __check_name(self): #私有方法
if self.name == '':return False
else:return True
def get_name(self):
if self.__check_name():
print(self.name,self.author)
else:
print('no value')
b=Book("Python程序设计教程",'bit',59)
b.get_name()
b.__check_name()
5.方法重载
Python本身是动态语言,方法的参数没有声明类型,参数的数量由可选参数和可变参数来控制。故Python对象方法不需要重载,定义一个方法即可实现多种调用。
示例:
class Person:
def say(self,name=None):
self.name=name
if name == None:
print("Hello!")
else:
print("Hello,my name is",self.name)
p=Person()
p.say()
p.say('Alex')
Python类体中定义多个重名不会报错,但只会保留最后一个方法。
示例
class Person:
def say(self,name):
print("hello,my name is",self.name)
def say(self,name,age):
print('hi,{0},age:{1}'.format(name,age))
p=Person()
p.say('Lisa',22)
p.say('Lisa')