Last active
February 14, 2018 23:12
-
-
Save osw4l/c10414789bb0589d1ed4a086cdb179e5 to your computer and use it in GitHub Desktop.
get the number of attributes with values that an object has
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Computer(object): | |
name = None | |
serial = None | |
model = None | |
kind = None | |
attrs_with_value = None | |
def __init__(self, *args, **kwargs): | |
self.name = kwargs.get('name', None) | |
self.serial = kwargs.get('serial', None) | |
self.model = kwargs.get('model', None) | |
self.kind = kwargs.get('kind', None) | |
self.attrs_with_value = 0 | |
@classmethod | |
def print_computers(cls, computers_): | |
for computer in computers_: | |
print('{} : {}'.format( | |
computer.name if computer.name else computer.kind, | |
computer.attrs_with_value | |
)) | |
macBookPro = Computer(name='MacBook Pro', | |
serial='FFX', | |
kind='Laptop') | |
iMac = Computer(kind='iMac 27.0', | |
model='2017') | |
clon = Computer(serial='FFX', kind='Desktop') | |
computers = [macBookPro, iMac, clon] | |
Computer.print_computers(computers) | |
for obj in computers: | |
print('\n') | |
for key, value in obj.__dict__.items(): | |
if value is not None: | |
if key != 'attrs_with_value': | |
print(key, value) | |
obj.attrs_with_value += 1 | |
print('\n') | |
Computer.print_computers(computers) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment