python3_绑定方法与非绑定方法的应用

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2018/5/21 22:56
# @Author  : chen
# @File    : 绑定方法与非绑定方法的应用.py

"""settings  # 另起一个文件名为settings
name = 'alex'
age = 18
sex = 'female'
"""

import settings
import time
import hashlib


class People:
    def __init__(self, name, age, sex):
        self.id = self.create_id()  # 这里的调用还是要用self开头
        self.name = name
        self.age = age
        self.sex = sex

    def tell_info(self):  # 绑定到对象的方法
        print('Name: %s Age: %s Sex: %s' % (self.name, self.age, self.sex))

    @classmethod
    def from_conf(cls):

        obj = cls(
            settings.name,
            settings.age,
            settings.sex
        )  # 这里的cls(settings.name, settings.age, settings.sex)可以看做创建对象
        return obj

    @staticmethod
    def create_id():
        m = hashlib.md5(str(time.time()).encode('utf-8'))  # 先要将time.time()转化成str类型,
        # hashlib只能针对byte类型进行操作, 所以需要进行encode.('utf-8)
        # Feeding string objects into update() is not supported, as hashes work on bytes, not on characters.
        return m.hexdigest()

# p = People('egon', 18, 'male')

# # 绑定给对象,就应该由对象来调用,会自动将对象本身当做第一个参数传入
# p.tell_info()  # tell_info(p)


# 绑定给类,就应该由类来调用,会自动将类本身当做第一个参数传入
# p = People.from_conf()  # from_conf(People)
# p.tell_info()


# 非绑定方法,不与类或者对象绑定,谁都可以调用,没有自动传值:一般用于"类"中不需要传值的情况
p1 = People('egon1', 18, 'male')
p2 = People('egon2', 28, 'male')
p3 = People('egon3', 38, 'male')

print(p1.id)
print(p2.id)
print(p3.id)

猜你喜欢

转载自blog.csdn.net/u013193903/article/details/80400048