Python初学者问题,什么是在0x处的类对象

huangapple go评论67阅读模式
英文:

Python noob question, what is class object at 0x

问题

以下是代码的翻译部分:

dogs = []
cats = []

class dog:
    def __init__(self, name):
        self.name = name
        dogs.append(self)

class cat:
    def __init__(self, name):
        self.name = name
        cats.append(self)

dog1 = dog("steve")
dog2 = dog("dave")

cat1 = cat("simon")
cat2 = cat("elizabeth")

print(dogs[0], cats[0])

如果我运行这段代码,它会给我返回:

[<__main__.dog object at 0x7fc51434c6a0>, <__main__.cat object at 0x7fc51434c700>]

这被称为什么?我想尝试使用该代码获取动物的名称。

之后,我想创建一个玩家可以购买宠物的功能,如果玩家输入"steve",它将使用上面的代码将dog("steve")添加到玩家的库存中。

我的问题是,我不知道这被称为什么。

英文:

My code is

dogs = []
cats = []

class dog:
    def __init__(self,name):
        self.name = name
        dogs.append(self)

class cat:
    def __init__(self,name):
        self.name = name
        cats.append(self)

dog1 = dog(&quot;steve&quot;)
dog2 = dog(&quot;dave&quot;)

cat1 = cat(&quot;simon&quot;)
cat2 = cat(&quot;elizabeth&quot;)

print(dogs[0], cats[0])

If i run this code it gives me

[&lt;__main__.dog object at 0x7fc51434c6a0&gt;, &lt;__main__.cat object at 0x7fc51434c700&gt;]

what is this called? and I want to try to get the name the animal use that code if i can

Later I want to have a player that can buy pets, and if player inputs "steve" it will add
dog("steve") to players inventory using the codes up there.

My problem is that I do not know what it is called

答案1

得分: 4

以下是您要翻译的代码部分:

你可以使用魔法方法 `__repr__` 来获取对象的字符串表示

dogs = []
cats = []

class dog:
    def __init__(self, name):
        self.name = name
        dogs.append(self)

    def __repr__(self):
        return self.name

class cat:
    def __init__(self, name):
        self.name = name
        cats.append(self)

    def __repr__(self):
        return self.name

dog1 = dog("steve")
dog2 = dog("dave")

cat1 = cat("simon")
cat2 = cat("elizabeth")
print(dogs)
print(cats)

输出:

[steve, dave]
[simon, elizabeth]
英文:

You can use magic method __repr__ to get the object str

dogs = []
cats = []

class dog:
    def __init__(self, name):
        self.name = name
        dogs.append(self)

    def __repr__(self):
        return self.name

class cat:
    def __init__(self, name):
        self.name = name
        cats.append(self)

    def __repr__(self):
        return self.name

dog1 = dog(&quot;steve&quot;)
dog2 = dog(&quot;dave&quot;)

cat1 = cat(&quot;simon&quot;)
cat2 = cat(&quot;elizabeth&quot;)
print(dogs)
print(cats)

output

[steve, dave]
[simon, elizabeth]

答案2

得分: 1

print将查找类实例的__str__函数并调用它(如果存在)。如果不存在,则会查找__repr__并调用它(如果存在)。如果这两个特殊方法都没有实现,您将获得类类型及其当前地址。

在类构造函数中附加到全局列表将起作用,但这不是一个很好的解决方案。

您应该以不同的方式考虑这个问题。您有两个类 - dog和cat。它们都代表动物。那么...为什么不创建一个动物类来保存共同的属性,然后为不同的动物类型创建子类。

类似于这样:

class Animal:
    def __init__(self, name: str):
        self.name = name
    def __str__(self):
        return f'I am a {type(self).__name__} and my name is {self.name}'


class dog(Animal):
    def __init__(self, name: str):
        super().__init__(name)


class cat(Animal):
    def __init__(self, name):
        super().__init__(name)


dogs = [dog('steve'), dog('dave')]
cats = [cat('simon'), cat('elizabeth')]


print(*(dogs+cats), sep='\n')

输出:

I am a dog and my name is steve
I am a dog and my name is dave
I am a cat and my name is simon
I am a cat and my name is elizabeth
英文:

print will look for a class instance's __str__ function and call that (if it exists). If that doesn't exist it will look for __repr__ and call that (if it exists). If neither of those dunder method have been implemented you'll get the class type and its current address.

Appending to a global list in a class constructor will work but it's not a great solution.

You should look at this in a different way. You have two classes - dog & cat. They both represent animals. So... why not have an animal class to hold common attributes then subclass that for your different animal types.

Something like this:

class Animal:
    def __init__(self, name: str):
        self.name = name
    def __str__(self):
        return f&#39;I am a {type(self).__name__} and my name is {self.name}&#39;


class dog(Animal):
    def __init__(self, name: str):
        super().__init__(name)


class cat(Animal):
    def __init__(self, name):
        super().__init__(name)


dogs = [dog(&#39;steve&#39;), dog(&#39;dave&#39;)]
cats = [cat(&#39;simon&#39;), cat(&#39;elizabeth&#39;)]


print(*(dogs+cats), sep=&#39;\n&#39;)

Output:

I am a dog and my name is steve
I am a dog and my name is dave
I am a cat and my name is simon
I am a cat and my name is elizabeth

答案3

得分: 0

在CPython中,这是对象所在的内存地址。

您可以添加一个__str__()和/或__repr__()方法来返回一个字符串以进行显示。

但通常更好的做法是让对象自己跟踪自己(使用内部集合),或者在将对象放入集合时自己管理,同时将对象的一部分放入外部集合中。

class Dog:
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return f"Dog({self.name})"

dogs = map(Dog, ("steve", "dave"))  # 映射
dogs = list(dogs)
>>> dogs
[Dog(steve), Dog(dave)]
>>> dogs[1].name
'dave'
英文:

in CPython, this is the memory address where the object is kept

You can add a __str__() and/or __repr__() method to return a string to display


However, it's generally better to have objects keep track of themselves (with an internal collection) or to put them into collections yourself, while you have the objects putting part of themselves into a collection external to them

class Dog:
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return f&quot;Dog({self.name})&quot;

dogs = map(Dog, (&quot;steve&quot;, &quot;dave&quot;))  # mapping
dogs = list(dogs)
&gt;&gt;&gt; dogs
[Dog(steve), Dog(dave)]
&gt;&gt;&gt; dogs[1].name
&#39;dave&#39;

答案4

得分: 0

你只是打印出对象,这将给你对象的字符串表示,默认情况下看起来像你在这里发布的样子。
如果你希望字符串表示仅提供狗/猫的名称,那么你必须重写__str__()__repr__()方法。

或者,你可以只打印出dogs[0].namecats[0].name,这是更常见的用法。

英文:

You are just printing out the objects, which gives you the string representation of the object which by default looks like what you have posted here.
If you want the string representation to give you just the name of the dog/cat then you have to override the __str__() or __repr__() method.

Alternatively you could just print out dogs[0].name and cats[0].name which is the more normal use case

huangapple
  • 本文由 发表于 2023年7月31日 19:17:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76803097.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定