私信  •  关注

Kris

Kris 最近创建的主题
Kris 最近回复了

您正在一个 print 作用因此,它将尝试打印该方法返回的值。因为你没有从这个方法返回任何东西,所以它会打印出来 None .

您总是可以返回值,而不是在内部打印它们。实例

class Employee:

    def __init__(self, first, last):
        self.first = first
        self.last = last

    def fullname(self):
        # just printing the name will not return the value.
        return '{} {}'.format(self.first, self.last)

    def email(self):
        # same, use a return statement to return the value.
        return '{}.{}@email.com'.format(self.first, self.last)


emp_1 = Employee('John', 'Smith')
emp_1.first = 'Jim'

print(emp_1.first)
print(emp_1.email())  # print what is returned by the method.
print(emp_1.fullname())

它将给出一个适当的输出,如

Jim
Jim.Smith@email.com
Jim Smith
4 年前
回复了 Kris 创建的主题 » 如何在python(pycharm)项目中向源代码添加路径

在Pycharm中,使用此流

source dir -&燃气轮机; Right-Click -&燃气轮机;选择 Mark Directory As Sources Root

它将使目录成为根目录并解决导入问题。

4 年前
回复了 Kris 创建的主题 » json。转储不使用自定义python对象

继承 json.JSONEncoder 不会使类可序列化。您应该单独定义编码器,然后在 json.dumps 呼叫

参见下面的示例方法

import json
from typing import Any


class Library:
    def __init__(self, name):
        print("calling Library constructor ")
        self.name = name

    def __repr__(self):
        # I have just created a serialized version of the object
        return '{"name": "%s"}' % self.name

# Create your custom encoder
class CustomEncoder(json.JSONEncoder):

    def default(self, o: Any) -> Any:
        # Encode differently for different types
        return str(o) if isinstance(o, Library) else super().default(o)


packages = [Library("package1"), Library("package2")]
data = {
    "simplefield": "value1",
    "complexfield": packages,
}
#Use your encoder while serializing
print(json.dumps(data, cls=CustomEncoder))

输出结果如下:

{"simplefield": "value1", "complexfield": ["{\"name\": \"package1\"}", "{\"name\": \"package2\"}"]}
6 年前
回复了 Kris 创建的主题 » 在Python中将png文件转换为动画gif

只有皮尔 (安装时使用: pip install Pillow ):

import glob
from PIL import Image

# filepaths
fp_in = "/path/to/image_*.png"
fp_out = "/path/to/image.gif"

# https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif
img, *imgs = [Image.open(f) for f in sorted(glob.glob(fp_in))]
img.save(fp=fp_out, format='GIF', append_images=imgs,
         save_all=True, duration=200, loop=0)