面试题系列(四)-- python魔法方法都有哪些?

问题:python魔法方法有哪些?

1、__dict__方法

class A(object):
a = 0
b = 1
def init(self):
self.a = 5
self.b = 6
def test(self):
print(“普通方法”)
@staticmethod
def static_test(self):
print(“静态方法”)
@classmethod
def class_test(self):
print(“类方法”)
obj = A()
print(A.dict)
print(obj.dict)
写了一个类和对象,分别打印类和对象的__dict__,看出现什么?

类调用__dict__

{‘module’: ‘main’, ‘a’: 0, ‘b’: 1,
init’: init at 0x0000010FE7035840>,
‘test’: ,
‘static_test’: ,
‘class_test’: ,
dict’: dict’ of ‘A’ objects>,
weakref’: weakref’ of ‘A’ objects>,
doc’: None}

对象调用__dict__

{‘a’: 5, ‘b’: 6}
类属性、类的普通方法、静态方法、类方法以及一些内置的属性都是放在类__dict__里的
对象的__dict__中存储了一些self.xxx的一些属性

2、str__方法
使用print输出对象的时候,初中初三一对一辅导只要自己定义了__str
(self)方法,那么就会打印__str__方法中return的数据
class Student(object):
#初始化对象
def init(self, new_name, new_age):
self.name = new_name
self.age = new_age
def str(self):
return “%s的年龄是:%d”%(self.name, self.age)

a = Student(“张三”,30)
print(a)

打印结果:
张三的年龄是:30

3、getattr、__setattr__方法

可以获取或者设置属性
class Student(object):
#初始化对象
def init(self, name, age):
self.name = name
self.age = age
def getattr(self):
return self.name
def setattr(self,name,value):
self.dict[“name”] = “add_{}”.format(value)
a = Student(“张三”,30)
print(a.dict)

打印结果:
{‘name’: ‘add_30’}

你可能感兴趣的:(面试题系列(四)-- python魔法方法都有哪些?)