[英]Referring to object names within its Class itself
My code: 我的代码:
import math
class Cal(object):
def __init__(self,precision):
self.precision=precision
def roundTo(self):
if(obj1):
return (round(math.pi,self.precision))
elif(obj2):
return (round(math.e,self.precision))
precision=int(raw_input("enter number:"))
obj1=Cal(precision)
answer1=obj1.roundTo()
print answer1
obj2=Cal(precision)
answer2=obj2.roundTo()
print answer2
My problem here is, I want the same method to return two different things on both the objects depending upon the object that is referenced. 我的问题是,我希望使用相同的方法根据引用的对象在两个对象上返回两个不同的东西。 Is there a way to do this:
有没有办法做到这一点:
def fun_name(self):
if(obj1):
#return
elif(obj2):
#return
I know the simpler way would be to create two different functions and assign each of them to individual objects. 我知道更简单的方法是创建两个不同的函数,并将每个函数分配给单个对象。 But is there a way to achieve this functionality?
但是有办法实现此功能吗?
Trying to identify objects by name looks like bad design, because an object does not know its own name. 试图通过名称标识对象看起来很糟糕,因为对象不知道自己的名称。 Look why it is impossible:
看看为什么不可能:
# let's have two objects with two names
obj1 = Cal()
obj2 = Cal()
# you can swap names
obj1, obj2 = obj2, obj1
# you can have two equally valid names for the same object
obj3 = obj1
# you can reuse a name for something else
obj2saved = obj2
obj2 = None
# and you can have objects without a name
obj_set = { Cal(), Cal() }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.