正确的写作方式
我正在尝试使用OOP python,并且我不确定__repr__函数的继承。 由于父类功能如下所示:
def __repr__(self):
'''Returns representation of the object'''
return("{}('{}')".format("Class name", self._param))
我想知道是否最好使用通用方法(也可以适用于儿童课程),如下所示:
def __repr__(self):
'''Returns representation of the object'''
return("{}('{}')".format(self.__class__.__name__, self._param))
或者如果在每个班级中重写该功能是一种很好的做法。
另外,请忽略编码部分,因为我将它留下。
那么__repr__在Pythons数据模型中有特殊含义:
object.__repr__(self)
由repr()内置函数调用以计算对象的“官方”字符串表示形式。 如果可能的话,这应该看起来像一个有效的Python表达式,可用于重新创建具有相同值的对象(给定适当的环境) 。 如果这是不可能的,应该返回一个<...some useful description...>形式的字符串。 返回值必须是一个字符串对象。 如果一个类定义了__repr__()而不是__str__() ,那么当需要该类的实例的“非正式”字符串表示时,也会使用__repr__() 。
这通常用于调试,因此重要的是表示信息丰富且毫不含糊。
这意味着__repr__返回的字符串应该可用于创建另一个对象。 所以__repr__是经常需要重写的东西,不是因为__class__.__name__而是因为必须在表示中捕获“状态”。
def class A(object):
def __init__(self, param):
self._param = param
def __repr__(self):
'''Returns representation of the object'''
return("{}('{}')".format(self.__class__.__name__, self._param))
那么当你为__init__添加参数时,你绝对应该覆盖__repr__ :
def class B(A):
def __init__(self, param1, param2):
self._param = param1
self._param2 = param2
def __repr__(self):
'''Returns representation of the object'''
return("{}('{}')".format(self.__class__.__name__, self._param, self._param2))
但是,如果超类的__repr__仍然准确地 “描述”子类,那么就没有必要重载__repr__ :
class B(A):
pass
然而,通过对类名进行硬编码来使用self.__class__.__name__总是一个不错的选择,以防万一您或其他人对它进行了子类化。
是的 - - 这不仅仅是“好的”,而且在几乎所有的项目和班级中都更实用。
实际上,这几乎是什么时候使用类继承的一个完美的“教科书示例”,并且只是让超类中的代码被重用。
在这里,你可以看看,我是如何从Student类的Pesron类继承__repr__方法的。
主要():
def main():
person_obj = Person("Jay", "26") #Instance of Person class
print(person_obj)
st_obj = Student("Jenny", "24", "12345") #Instance of Student class
print(st_obj)
基类:Person
class Person:
name = ""
age = 0
def __init__(self, personName, personAge):
self.name = personName
self.age = personAge
def __repr__(self):
return "Hello.. greeting!! {} {} ".format(self.name, self.age)
派生类:学生
class Student(Person):
studentId = ""
def __init__(self, studentName, studentAge, studentId):
Person.__init__(self, studentName, studentAge)
self.studentId = studentId
def __repr__(self):
return super().__repr__() + " id is: {} ".format(self.studentId)
if __name__ == '__main__':
main()
链接地址: http://www.djcxy.com/p/96405.html
上一篇: Correct way to write
下一篇: How can I fix impaired functionality caused by disallowed useragent?
