简体   繁体   English

有没有办法在 Python 中获取已使用 self 和 append 数据初始化的列表属性?

[英]Is there a way to grab list attributes that have been initialized using self and append data to them in Python?

I have a class in Python that initializes the attributes of an environment.我在 Python 中有一个 class 用于初始化环境的属性。 I am attempting to grab the topographyRegistry attribute list of my Environment class in a separate function, which when called, should take in the parameters of 'self' and the topography to be added.我试图在一个单独的 function 中获取我的环境 class 的 topographyRegistry 属性列表,调用它时,应该接受“self”参数和要添加的地形。 When this function is called, it should simply take an argument such as addTopographyToEnvironment(self, "Mountains") and append it to the topographyRegistry of the Environment class. When implementing what I mentioned above, I ran into an error regarding the 'self' method not being defined.当这个 function 被调用时,它应该简单地采用诸如 addTopographyToEnvironment(self, "Mountains") 和 append 之类的参数到环境的 topographyRegistry class。在实现我上面提到的内容时,我遇到了关于“自我”的错误方法未定义。 Hence, whenever I call the above line, it gives me:因此,每当我调用上面的行时,它都会给我:

    print (Environment.addTopographyToEnvironment(self, "Mountains"))
                                                  ^^^^
NameError: name 'self' is not defined

This leads me to believe that I am unaware of and missing a step in my implementation, but I am unsure of what that is exactly.这让我相信我没有意识到并遗漏了我实施中的一个步骤,但我不确定那到底是什么。 Here is the relevant code:这是相关代码:

class EnvironmentInfo:
    def __init__(self, perceivableFood, perceivableCreatures, regionTopography, lightVisibility):
        self.perceivableFood = perceivableFood
        self.perceivableCreatures = perceivableCreatures
        self.regionTopography = regionTopography
        self.lightVisibility = lightVisibility

class Environment:
    def __init__(self, creatureRegistry, foodRegistry, topographyRegistery, lightVisibility):
        logging.info("Creating new environment")
        self.creatureRegistry = []
        self.foodRegistry = []
        self.topographyRegistery = []
        self.lightVisibility = True

    def displayEnvironment():
        creatureRegistry = []
        foodRegistry = []
        topographyRegistery = ['Grasslands']
        lightVisibility = True
        print (f"Creatures: {creatureRegistry} Food Available: {foodRegistry} Topography: {topographyRegistery}  Contains Light: {lightVisibility}")

    def addTopographyToEnvironment(self, topographyRegistery):
        logging.info(
            f"Registering {topographyRegistery} as a region in the Environment")
        self.topographyRegistery.append(topographyRegistery)

    def getRegisteredEnvironment(self):
        return self.topographyRegistry

if __name__ == "__main__":
        print (Environment.displayEnvironment())                         #Display hardcoded attributes
        print (Environment.addTopographyToEnvironment(self, "Mountains"))#NameError
        print (Environment.getRegisteredEnvironment(self))               #NameError

What am I doing wrong or not understanding when using 'self'?使用“自我”时我做错了什么或不理解什么?

Edit: In regard to omitting 'self' from the print statement, it still gives me an error indicating a TypeError:编辑:关于从 print 语句中省略“self”,它仍然给我一个错误,指示 TypeError:

 print (Environment.addTopographyToEnvironment("Mountains"))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Environment.addTopographyToEnvironment() missing 1 required positional argument: 'topographyRegistery'

Comments注释

  • Despite having def getRegisteredEnvironment(self): it wasn't indented, so it's not recognized as a class method.尽管有def getRegisteredEnvironment(self):它没有缩进,所以它不被识别为 class 方法。
  • self is a keyword used in conjunction with classes (class methods or attributes) - not functions. self是与类(类方法或属性)结合使用的关键字 - 而不是函数。 self is implied to be the instantiated object (eg a = Environment(...) -> self would refer to a ) or the module's (I can't think of the proper term) class. self被暗示为实例化的 object(例如a = Environment(...) -> self 将引用a )或模块的(我想不出合适的术语)class。
  • You didn't have your addTopographyToEnvironment class method defined.您没有定义addTopographyToEnvironment class 方法。
  • In terms of your Environment class, you aren't using the variables you are passing to the class, so I made that change as well - I don't know if that was intentional or not.就您的环境 class 而言,您没有使用传递给 class 的变量,所以我也进行了更改 - 我不知道这是不是故意的。
  • As per your comment from the other answer, if you had def my_class_method(self) and you try to invoke it through an object with additional parameters, like so a = my_object(); a.my_class_method("Mountains")根据您对其他答案的评论,如果您有def my_class_method(self)并尝试通过带有附加参数的 object 调用它,例如a = my_object(); a.my_class_method("Mountains") a = my_object(); a.my_class_method("Mountains") , you should get an error of the sorts, "2 positional arguments passed, expected 1.". a = my_object(); a.my_class_method("Mountains") ,你应该会得到这样的错误,“2 positional arguments passed, expected 1.”。
  • Your main problem is that you are doing Environment.class_method() and not creating an object from the class. Do a = Environment(whatever arguments here) to create an object from the class, then do a.addTopographyToEnvironment("Mountains") to do what you were going to do with "Mountains" and that object. What you have currently may be right, its just is missing the proper implementation, but the below article does a great job explaining the differences between all of them (Class Methods vs Static Methods vs Instance Methods), and is definitely worth the read.您的主要问题是您正在执行Environment.class_method()而不是从 class 创建 object。执行a = Environment(whatever arguments here)从 class 创建 object,然后执行a.addTopographyToEnvironment("Mountains") (做你想用“山脉”和那个 object 做的事情。你目前拥有的可能是正确的,它只是缺少正确的实现,但下面的文章很好地解释了它们之间的区别(类方法与Static 方法与实例方法),绝对值得一读。
class EnvironmentInfo:
    def __init__(self, perceivableFood, perceivableCreatures, regionTopography, lightVisibility):
        self.perceivableFood = perceivableFood
        self.perceivableCreatures = perceivableCreatures
        self.regionTopography = regionTopography
        self.lightVisibility = lightVisibility

class Environment:
    def __init__(self, creatureRegistry, foodRegistry, topographyRegistery, lightVisibility):
        logging.info("Creating new environment")
        self.creatureRegistry = creatureRegistry
        self.foodRegistry = foodRegistry
        self.topographyRegistery = topographyRegistery
        self.lightVisibility = lightVisibility

    def displayEnvironment(self):
        creatureRegistry = []
        foodRegistry = []
        topographyRegistery = ['Grasslands']
        lightVisibility = True
        print (f"Creatures: {creatureRegistry} Food Available: {foodRegistry} Topography: {topographyRegistery}  Contains Light: {lightVisibility}")

    def addTopographyToEnvironment(self, environment):
        return "Whatever this is supposed to return." + environment

    def getRegisteredEnvironment(self):
        return self.topographyRegistry

if __name__ == "__main__":
        print (Environment.displayEnvironment())                         #Display hardcoded attributes
        print (Environment.addTopographyToEnvironment("Mountains"))#NameError
        print (Environment.getRegisteredEnvironment())               #NameError

Object Instantiation In Python Object 实例化 Python

With all that out of the way, I will answer the question as is posed, "Is there a way to grab list attributes that have been initialized using self and append data to them in Python?".有了所有这些,我将回答所提出的问题,“有没有办法在 Python 中获取已使用 self 和 append 数据初始化的列表属性?”。 I am assuming you mean the contents of the list and not the attributes of it, the attributes would be "got" or at least printed with dir()我假设你的意思是列表的内容而不是它的属性,属性将是“得到”或者至少用dir()打印

As a simple example:举个简单的例子:

class MyClass:
    def __init__(self, my_list):
        self.my_list = my_list


if __name__ == "__main__":
    a = MyClass([1, 2, 3, 4, 5])
    print(a.my_list)
    # will print [1, 2, 3, 4, 5]
    a.my_list.append(6)
    print(a.my_list)
    # will print [1, 2, 3, 4, 5, 6]
    print(dir(a.my_list))
    # will print all object methods and object attributes for the list associated with object "a".

Sub Classing In Python Python 中的子类

Given what you have above, it looks like you should be using method sub classing - this is done with the keyword super .鉴于以上内容,看起来您应该使用方法子类化——这是通过关键字super完成的。 From what I can guess, it would look like you'd implement that kind of like this:据我猜测,看起来你会像这样实现:

class EnvironmentInfo:
    def __init__(self, perceivableFood, perceivableCreatures, regionTopography, lightVisibility):
        self.perceivableFood = perceivableFood
        self.perceivableCreatures = perceivableCreatures
        self.regionTopography = regionTopography
        self.lightVisibility = lightVisibility

class Environment(EnvironmentInfo):
    def __init__(self, creatureRegistry, foodRegistry, topographyRegistery, lightVisibility, someOtherThingAvailableToEnvironmentButNotEnvironmentInfo):
        logging.info("Creating new environment")
        super.__init__(foodRegistry, creatureRegistry, topographyRegistery, lightVisibility)
        self.my_var1 = someOtherThingAvailableToEnvironmentButNotEnvironmentInfo

    def displayEnvironment(self):
        creatureRegistry = []
        foodRegistry = []
        topographyRegistery = ['Grasslands']
        lightVisibility = True
        print (f"Creatures: {creatureRegistry} Food Available: {foodRegistry} Topography: {topographyRegistery}  Contains Light: {lightVisibility}")

    def addTopographyToEnvironment(self, environment):
        return "Whatever this is supposed to return." + environment

    def getRegisteredEnvironment(self):
        return self.topographyRegistry

    def methodAvailableToSubClassButNotSuper(self)
        return self.my_var1

if __name__ == "__main__":
    a = Environment([], [], [], True, "Only accessible to the sub class")
    print(a.methodAvailableToSubClassButNotSuper())

as the article describes when talking about super() , methods and attributes from the super class are available to the sub class.正如文章在谈论super()时所描述的,来自超级class方法和属性可用于class。


Extra Resources额外资源

Class Methods vs Static Methods vs Instance Methods - "Difference #2: Method Defination" gives an example that would be helpful I think. Class 方法与 Static 方法与实例方法- “差异 #2:方法定义”给出了一个我认为有用的示例。

What is sub classing in Python?Python 中的子类是什么? - Just glanced at it; - 只是扫了一眼; probably an okay read.可能还可以阅读。

Self represents the instance of the class and you don't have access to it outside of the class, by the way when you are calling object methods of a class you don't need to pass self cause it automatically be passed to the method you just need to pass the parameters after self so if you want to call an object method like addTopographyToEnvironment(self, newVal) you should do it like: Self 代表 class 的实例,您无法在 class 之外访问它,顺便说一句,当您调用 class 的 object 方法时,您不需要传递 self,因为它会自动传递给您的方法只需要在 self 之后传递参数,所以如果你想调用 object 方法,比如addTopographyToEnvironment(self, newVal)你应该这样做:

Environment.addTopographyToEnvironment("Mountains")

and it should work fine它应该工作正常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM