class - __init__ Constructor in Python -


i trying write constructor class "block" stores coordinates of center of block (either separate x- , y-coordinates or pair of numbers) , width , height of block. problem having writing init can either take tuple of coordinates x,y or individual numbers x , y.

here have far:

 def __init__(self,(x,y),height,width): 

use keyword arguments:

class blocks(object):     def __init__(self, center=none, x=none, y=none, height=0, width=0):         if center none:             # x , y must set             if x none or y none:                 raise typeerror('you must either specify center or both x , y')         else:             # center set, x , y must not             if x not none or y not none:                 raise typeerror('you must either specify center or both x , y')             x, y = center         # here have x , y set 

now can use blocks(center=(10, 20)) or can use blocks(x=10, y=20). height , width have defaults, can overridden.

the alternative use class method:

class blocks(object):     def __init__(self, x, y, height, width):         # here have x , y set      @classmethod     def from_center(cls, center, height, width):         x, y = center         return cls(x, y, height, width) 

and use either:

block_one = block(10, 20, 5, 5) 

or

block_two = block.from_center((10, 20), 5, 5) 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -