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

查看:28
本文介绍了在类 __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天全站免登陆