相关疑难解决方法(0)

如何使用print()打印类的对象?

我正在学习Python中的绳索.当我尝试Foobar使用该print()函数打印类的对象时,我得到如下输出:

<__main__.Foobar instance at 0x7ff2a18c>
Run Code Online (Sandbox Code Playgroud)

有没有办法可以设置及其对象打印行为(或字符串表示)?例如,当我调用类对象时,我想以某种格式打印其数据成员.如何在Python中实现这一点?print()

如果您熟悉C++类,则可以通过为类ostream添加friend ostream& operator << (ostream&, const Foobar&)方法来实现上述标准.

python printing class object

489
推荐指数
11
解决办法
68万
查看次数

Python3.5中的__metaclass__

在Python2.7这个代码可以很好地工作,__getattr__MetaTable 运行.但是在Python 3.5中它不起作用.

class MetaTable(type):
    def __getattr__(cls, key):
        temp = key.split("__")
        name = temp[0]
        alias = None

        if len(temp) > 1:
            alias = temp[1]

        return cls(name, alias)


class Table(object):
    __metaclass__ = MetaTable

    def __init__(self, name, alias=None):
        self._name = name
        self._alias = alias


d = Table
d.student__s
Run Code Online (Sandbox Code Playgroud)

但是在Python 3.5中我得到了一个属性错误:

Traceback (most recent call last):
  File "/Users/wyx/project/python3/sql/dd.py", line 31, in <module>
    d.student__s
AttributeError: type object 'Table' has no attribute 'student__s'
Run Code Online (Sandbox Code Playgroud)

python metaclass

12
推荐指数
1
解决办法
8738
查看次数

我可以为类而不是实例定义__repr__吗?

我可以__repr__为类而不是实例定义一个吗?例如,我正在尝试这样做

class A(object):
    @classmethod
    def __repr__(cls):
        return 'My class %s' % cls
Run Code Online (Sandbox Code Playgroud)

我得到的是

In [58]: a=A()

In [59]: a
Out[59]: My class <class '__main__.A'>

In [60]: A
Out[60]: __main__.A
Run Code Online (Sandbox Code Playgroud)

我试图让第60行的输出看起来像"我的A类",而不是实例a.我想这样做的原因是我使用Python的元类生成了很多类.而且我想要一种更易读的方法来识别类而不是股票代理.

python metaprogramming metaclass

11
推荐指数
1
解决办法
2434
查看次数

python:改变类的打印

是否有可能在python中更改为类打印的内容.我知道如果我们提供__str__ __unicode__方法,我们可以改变打印类的实例的方式.但我想为一堂课做这件事

例如:

class A(object):
    def __str__(self):
        return 'hello'

a = A()
print a
Run Code Online (Sandbox Code Playgroud)

将打印hello.是否可以更改print A默认情况下打印的行为<class '__main__.A'>

更新:我想我也可以解释一下上下文.我正在尝试创建MySQL查询,我有表示表的类.这些表类中的每一个都有一个包含表名的类变量.所以我想要做的是能够将Class as参数传递给cursor.execute并在查询中替换表名.

python mysql printing class object

7
推荐指数
1
解决办法
347
查看次数

运算符可以作为python中的类方法重载吗?

为了使扩展看起来很干净,我试图在python中实现">>"运算符作为类方法.我不知道怎么回事.我不想创建一个实例,因为我真的在类本身上运行.

>>> class C:
...     @classmethod
...     def __rshift__(cls, other):
...         print("%s got %s" % (cls, other))
...
>>> C.__rshift__("input")
__main__.C got input
>>> C() >> "input"
__main__.C got input
>>> C >> "input"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for >>: 'classobj' and 'str'
Run Code Online (Sandbox Code Playgroud)

背景资料:

我试图在peewee ORM中实现视图(类似于Django).Peewee允许您将数据库表及其关系定义为类,如下所示:

class Track(Model):
    title = CharField()
    artist = ForeignKeyField(Artist)

class Artist(Model):
    name = CharField(unique = True)
    location = ForeignKeyField(Location)

class Location(Model):
    state = CharField(size …
Run Code Online (Sandbox Code Playgroud)

python class operator-overloading peewee

6
推荐指数
1
解决办法
636
查看次数

Racket中自定义数据的字符串表示

我喜欢你如何在透明结构中保留表示:

(struct posn (x y)
        #:transparent)

> (posn 1 2)
(posn 1 2)
Run Code Online (Sandbox Code Playgroud)

但有没有办法定制它?像在Python中一样?

string scheme representation racket

5
推荐指数
1
解决办法
422
查看次数

从列表中打印 __init__ 对象 Python 错误

我正在尝试根据我的班级设置从列表中打印对象。

from math import *
import time

class MyClass:
    def __init__(self, name, age):
        self.name = name
        self.age = age

people = [MyClass("David",17),
MyClass("George",63),
MyClass("Zuck",12),
MyClass("Mark",18)
]

print(people[2])
Run Code Online (Sandbox Code Playgroud)

但它打印出这个: < main .MyClass object at 0x0000000003129128> 我希望它打印“Zuck”

python

5
推荐指数
1
解决办法
1195
查看次数

是否可以为Python中的类设置默认方法?

假设你有一个 python 类。我们就这样称呼它C。假设您在脚本中的某个位置或以交互模式创建了它的实例:c=C()

类中是否可以有一个“默认”方法,这样当您引用实例时,就会调用该默认方法?

class C(object):
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def method0(self):
        return 0
    def method1(self):
        return 1
    def ...
        ...
    def default(self):
        return "Nothing to see here, move along"
Run Code Online (Sandbox Code Playgroud)

等等。

现在我以交互模式创建该类的实例,并引用它:

>>> c=C(3,4)
>>> c
<__main__.C object at 0x6ffffe67a50>
>>> print(c)
<__main__.C object at 0x6ffffe67a50>
>>>
Run Code Online (Sandbox Code Playgroud)

如果您单独引用该对象,是否可以有一个被调用的默认方法,如下所示?

>>> c
'Nothing to see here, move along'
>>> print(c)
Nothing to see here, move along
>>>
Run Code Online (Sandbox Code Playgroud)

python methods class

4
推荐指数
1
解决办法
1万
查看次数

Python 3中类的字符串表示形式

我希望我的类有一个基于类变量的字符串表示(在派生类中可能有所不同).这个答案表明,元类可能是要走的路:

class MC(type):
    def __repr__(self):
        return 'Wahaha!'

class C():
    __metaclass__ = MC

print(C)
Run Code Online (Sandbox Code Playgroud)

但这在Python 3中不起作用,返回

<class '__main__.C'>
Run Code Online (Sandbox Code Playgroud)

而不是Wahaha!.有人可以向我解释Python 2和3之间的变化以及如何在Python 3中进行更改吗?

python class representation class-variables python-3.x

3
推荐指数
1
解决办法
137
查看次数

如何在Python中不实例化对象的情况下打印类属性?

根据这篇文章,我可以通过访问枚举实例变量str(self.__dict__),但我不知道如何使用类变量来做到这一点。

这是我想避免的

# I would like to print out class attributes by overriding `__str__` for that class.
class circle(object):
    radius = 3
    def __str__(self):     # I want to avoid instantiation like this.
        return str(circle.radius)

print(circle())    # I want to avoid instantiation. why can't I just print(circle)?
Run Code Online (Sandbox Code Playgroud)

python oop class

3
推荐指数
1
解决办法
2811
查看次数

错误:&lt;__main__.Node object at 0x03A5F990&gt; 使用链表时

以下是使用 Python 的链表实现:

class Node:
    def __init__(self,data,next):
        self.data = data
        self.next = next

class List:
    head=None
    tail=None
    def printlist(self):
        print("list")
        a=self.head
        while a is not None:
                print(a)
                a=a.next

    def append(self, data):
        node = Node(data, None)
        if self.head is None:
            self.head = self.tail = node
        else:
            self.tail.next = node
        self.tail = node

p=List()
p.append(15)
p.append(25)
p.printlist()
Run Code Online (Sandbox Code Playgroud)

输出:

list
<__main__.Node object at 0x03A9F970>
<__main__.Node object at 0x03A9F990>
Run Code Online (Sandbox Code Playgroud)

要检查您的答案,您需要编辑此内置方法def __repr__并重写它。

您也可以通过添加__str__方法来做到这一点

python linked-list object data-structures

2
推荐指数
1
解决办法
9730
查看次数

为类运行初始化程序

我不太确定这个问题的好标题是什么,所以我会解释我想做什么.

我想要一个类,可以通过某种方式实例化:

class Setting(int):
  def __init__(self, value, description=None):
    super(Setting, self).__init__(value)
    self.description = description

max_memory = Setting(5, description="The maximum memory we can use")

print s + 5 # 10
print s.description # The maximum memory we can use
Run Code Online (Sandbox Code Playgroud)

但是,我希望这适用于所有对象,所以我可以只有一个类.这样我就可以让对象的行为与底层value对象完全相同,但只是附加description属性.

我尝试将上面改为:

class Setting(object):
  def __init__(self, value, description=None):
    type(value).__init__(value)
    self.description = description

s = Setting(5)

print s + 5
print s.description
Run Code Online (Sandbox Code Playgroud)

但现在我收到了错误:

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print s + 5
TypeError: unsupported …
Run Code Online (Sandbox Code Playgroud)

python python-3.x

1
推荐指数
1
解决办法
96
查看次数