这是我第一次在这个网站上寻求帮助.我在这里寻找答案,但没有什么能真正为我清除.
我正在努力学习Python.我在"课堂"一章.以下代码:
class Character:
def __init__(self, name, initial_health):
self.name = name
self.health = initial_health
self.inventory = []
def __str__(self):
s = "Name: " + self.name
s += "| Health: " + str(self.health)
s += "| Inventory: " + str(self.inventory)
return s
def grab(self, item):
self.inventory.append(item)
me = Character("vic", 37)
me.grab("pencil")
me.grab("paper")
print str(me)
Run Code Online (Sandbox Code Playgroud)
...生产:
Name: vic| Health: 37| Inventory: ['pencil', 'paper']
Run Code Online (Sandbox Code Playgroud)
但是下面的代码,在我看来非常相似,打印出内存位置而不是变量本身:
import random
SUITS = ['C', 'S', 'H', 'D']
RANKS = ['A', '2', '3', '4', '5', '6', '7', '8', …Run Code Online (Sandbox Code Playgroud) 我通常会写一个 a__repr__作为展示如何重新创建实例的方式。例如:
class Component:
def __init__(self, start, end):
self.start = start
self.end = end
def __repr__(self):
return f'{self.__class__.__name__}(start={self.start}, end={self.end})'
Run Code Online (Sandbox Code Playgroud)
是否有一种“标准”的方式来编写__repr__,如果没有,是否有关于如何编写的建议选项/最佳实践,或者它完全是主观的?
假设我有一个Graph类和一个Vertex类,定义如下
Graph.py
class Graph:
def __init__(self):
self.adjacencyList = {}
def __str__(self):
return str(self.adjacencyList)
def addVetex(self,key,value):
if Vertex(key,value) not in self.adjacencyList:
self.adjacencyList[Vertex(key,value)] = []
Run Code Online (Sandbox Code Playgroud)
Vertex.py
class Vertex:
def __init__(self,key,value):
self.key = key
self.value = value
def __str__(self):
return "Key: ",str(self.key)," Value: ",str(self,value)
def __hash__(self):
return self.key
Run Code Online (Sandbox Code Playgroud)
如果我这样做:
G = Graph()
G.addVetex(1,None)
G.addVetex(2,None)
G.addVetex(1,3)
print G
Run Code Online (Sandbox Code Playgroud)
打印出来{<Vertex.Vertex instance at 0x110295b90>: [], <Vertex.Vertex instance at 0x110295bd8>: []}但是我期待着类似的东西{"Key:1 Value:None":[]...}
我的问题是我做错了什么?当一个词被打印出来时,为什么它不会尝试调用其键/值的str函数?
谢谢.
我刚刚遇到这个问题,在Python和它之间的差异,__str__并__repr__提到它的主要目的__repr__是明确的.但是我听说它的主要目的__repr__是生成一个字符串,以便以后eval()可以重建python对象.其实主要目的是__repr__什么?python中的任何内置函数或任何默认模块本身都__repr__用于重构对象吗?如果我们只是覆盖__repr__它会一直返回一个常量字符串(例如"foo"),它会搞砸执行吗?
我有这个类与分数一起工作(例如(1,2),(3,4)等):
class Fraction(object):
def __init__(self, num=0, denom=1):
''' Creates a new Fraction with numberator num and denominator denom'''
self.numerator = num
if denom != 0:
self.denominator = denom
else:
raise ZeroDivisionError
def __str__(self):
'''Returns the string numerator/denominator '''
return "{0}/{1}".format(self.numerator, self.denominator)
def __repr__(self):
"""blah"""
return Fraction(self.numerator, self.denominator)
Run Code Online (Sandbox Code Playgroud)
我希望有一个子类混合数,它可以接受整数和分数(例如2分数(1,2),3分数(3,4)等).我不知道如何做到这一点,任何有关如何做到这一点的帮助将不胜感激
class MixedNumber(Fraction):
Run Code Online (Sandbox Code Playgroud) 我创建了这个生成器函数:
def myRange(start,stop,step):
r = start
while r < stop:
yield r
r += step
Run Code Online (Sandbox Code Playgroud)
我用两种不同的方式使用它.第一名:
for x in myRange(0,1,0.1):
print x
Run Code Online (Sandbox Code Playgroud)
结果:
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
Run Code Online (Sandbox Code Playgroud)
第二种方式调用函数:
a = [x for x in myRange(0,1,0.1)]
Run Code Online (Sandbox Code Playgroud)
这导致:
[0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6, 0.7, 0.7999999999999999, 0.8999999999999999, 0.9999999999999999]
Run Code Online (Sandbox Code Playgroud)
为什么生成的值不同?
我怎样才能定义一个类,使对象名可以用作变量?我正在编写一个数值分析类,它只包含一个numpy数组作为即时变量和许多数学运算.为了方便和可读性,仅仅通过它的对象名访问numpy数组会很不错.例如,可以直接调用numpy数组(或来自matplotlib,pandas等许多其他包的对象),
import numpy as np
foo = np.array([[1,2],[3,4]])
print foo
Run Code Online (Sandbox Code Playgroud)
这就像我所拥有的(省略了定义方法)
import numpy as np
class MyClass():
def __init__(self, input_array):
self.data = np.array(input_array)
foo = MyClass([[1,2],[3,4]])
print foo
print foo.data
Run Code Online (Sandbox Code Playgroud)
这将foo打印为foo.data的指针和内容
<__main__.MyClass instance at 0x988ff0c>
[[1 2]
[3 4]]
Run Code Online (Sandbox Code Playgroud)
我尝试self = np.array(input_array)了构造函数,但它仍然给出了一个地址.我在想像重载对象名称,但我找不到任何信息.
如果不可能,那么这些包怎么能实现呢?我试着读一些numpy和pandas的源代码.但作为python的新手,我几乎不可能在那里找到答案.
编辑
感谢CoryKramer和ŁukaszR.建议使用__str__和__repr__.但我意识到我真正需要的是继承numpy.ndarray甚至是pandas DataFrame,以便继承所有数学函数.我发现这两个环节非常有帮助,对ndarray和对数据帧,以tweek __init__我的接口调用.
在python中,是否有针对__str__返回多行字符串的方法的PEP的一部分?
亲: PyCharm没有告诉我,谷歌画了一个空白
反对:我可以看到,如果有人连接它,感觉不是pythonic并且我不确定我能记得在我自己的代码中看到一个-bar,它会导致不优雅的反应
因此,我不确定是否只有多行__str__返回(保持简单)或单独留下__str__(即返回<class foo>)并具有特殊模块(例如 foo.report()).
我有一个自定义类,如:
class foo(object):
def __init__(self, name):
self.__name = name
def get_name(self):
return self.__name
Run Code Online (Sandbox Code Playgroud)
我想做的是写
test = foo("test")
print test
Run Code Online (Sandbox Code Playgroud)
代替
test = foo("test")
print test.get_name()
Run Code Online (Sandbox Code Playgroud)
这样做的神奇方法是什么?
我想将 N 个字符串加入新字符串。每个项目一行:
my_list=['one', 'two', 'three']
lines='\n'.join(my_list)
Run Code Online (Sandbox Code Playgroud)
不幸的是,我需要在每行末尾添加一个尾随换行符 lines. 在上述解决方案中,最后一行缺少换行符。
我搜索了一个简单且新手友好的解决方案。
...我使用 Python 2.7
python ×10
python-3.x ×2
string ×2
class ×1
dictionary ×1
function ×1
generator ×1
oop ×1
pep8 ×1
repr ×1
subclassing ×1