简体   繁体   English

在类本身中引用对象名称

[英]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.

相关问题 重命名类本身内的类对象名称 - Rename class object name within class itself 通过字符串引用类名? - Referring to class names through strings? 在Django中,对于同一类的两个对象之间的OneToOne关系,是否可以防止某个对象在数据库级别引用其自身? - In Django, for a OneToOne relationship between two objects of the same class, can an object be prevented from referring to itself at the db level? 如何从类本身内部实例化一个类的对象? - How to instantiate an object of a class from within the class itself? 让 class object 从其包含结构中移除自身 - Have a class object remove itself from its containing structure Java转换为Jython - 在自身中获取类对象 - Java converting to Jython-Getting a class object within itself python,字典值是对象,该对象可以从自身内部的函数访问其自己的键值吗? - python, dictionary value is object, can that object access its own key value from a function within itself? 父类如何在Python中调用自己的方法 - How would a parent class call its own method within itself in Python 为什么在Python中没有从对象的方法中引用对象成员的捷径? - Why is there no shorthand for referring the object's members from its methods in Python? 如何为所有功能更改对象在功能中所指的内容 - How to change what an object is referring to within a function for all functions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM