在类__init中获取实例名__() [英] Getting an instance name inside class __init__()

查看:275
本文介绍了在类__init中获取实例名__()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中构建新的类对象时,我希望能够基于类的实例名称创建一个默认值,而不需要传入额外的参数。我该如何做到这一点?这里是我试图的基本伪代码:

While building a new class object in python, I want to be able to create a default value based on the instance name of the class without passing in an extra argument. How can I accomplish this? Here's the basic pseudo-code I'm trying for:

class SomeObject():
    defined_name = u""

    def __init__(self, def_name=None):
        if def_name == None:
            def_name = u"%s" % (<INSTANCE NAME>)
        self.defined_name = def_name

ThisObject = SomeObject()
print ThisObject.defined_name   # Should print "ThisObject"


推荐答案

实例没有名称。当全局名 ThisObject 获得绑定到通过评估 SomeObject 构造函数已经完成运行。

Instances don't have names. By the time the global name ThisObject gets bound to the instance created by evaluating the SomeObject constructor, the constructor has finished running.

如果你想要一个对象有一个名字,只需在构造函数中传递名字。

If you want an object to have a name, just pass the name along in the constructor.

def __init__(self, name):
    self.name = name

这篇关于在类__init中获取实例名__()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆