[英]Using instance name in str() function of a class
I wrote a class about points in cartesian system (each point instance having abscissa and ordinate) and each instance has its name, for example we have point 'A' (coordinates (2,3)) and 'B'(coordinates(1,2)).我写了一个关于笛卡尔系统中点的类(每个点实例都有横坐标和纵坐标),每个实例都有它的名字,例如我们有点'A'(坐标(2,3))和'B'(坐标(1, 2))。 In the str () function i need to use the name of the instance to have a nice output.
在str () 函数中,我需要使用实例的名称来获得不错的输出。 For example i need the program to print out ( Abscissa of A is 2) when using the print command (print(A)) And displaying ( Abscissa of B is 1) when (print(B)) is written in main script.
例如,我需要程序在使用打印命令 (print(A)) 时打印出(A 的横坐标为 2)并在主脚本中编写(print(B))时显示(B 的横坐标为 1)。 The main problem is to have the name of instance displayed.
主要问题是显示实例的名称。 Is there a function that returns the name of instance of a certain class?
是否有返回某个类的实例名称的函数?
I tried using self.namehex(id(self)) in the init() function and then use self.name() but it didn't do the trick我尝试在 init() 函数中使用 self.namehex(id(self)) 然后使用 self.name() 但它没有成功
As @chepner commented, objects don't know the names they're assigned.正如@chepner 评论的那样,对象不知道它们被分配的名称。
If you want your Point class to know its instance name, add it as an argument to __init__()
.如果您希望 Point 类知道其实例名称,请将其作为参数添加到
__init__()
。
class Point(object):
def __init__(self, name, x, y):
self.name = name
...
def __str__(self):
return 'abcissa of %s is ...' % self.name
a = Point('a', 50, 100)
You need to implement the repr or str method.您需要实现repr或str方法。 repr is used when you use print on the object and str when you use str(object).
当您在使用STR(对象)使用的打印对象和STR在再版时使用。
class SomeClass:
def __init__(self, name, x, y):
self.name = name
self.x = x
self.y = y
def __repr__(self):
return f'abscissa of name: {self.name} is...'
def __str__(self):
return f'abscissa of name: {self.name} is...'
OUTPUT:输出:
a = SomeClass('name', 4, 6) b = SomeClass('name2', 9, 8) a = SomeClass('name', 4, 6) b = SomeClass('name2', 9, 8)
a abscissa of name: name is... b abscissa of name: name2 is... str(a) 'abscissa of name: name is...' str(b) 'abscissa of name: name2 is...' a 姓名横坐标:name 是... b 姓名横坐标:name2 是... str(a) '姓名横坐标:name 是...' str(b) '姓名横坐标:name2 是...'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.