首页 > 编程语言 >Python - Creating alternative initializers using class Methods

Python - Creating alternative initializers using class Methods

时间:2024-07-30 16:41:28浏览次数:6  
标签:__ Creating Python age methods Person initializers class name

Class methods allow us to define alternative initializers (also known as factory methods) in a class. These methods help us create instance objects from different types of input data. Let us understand this with the help of an example. Again, we take the same Person class. We have deleted the class variables to keep it short and simple.

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

    def display(self):
        print(f'{self.name} is {self.age} years old')

p1 = Person('Devanshi', 18)
p2 = Person('Devank', 10)

We can initialize a new instance object of this Person class in only one way, by providing values of name and age. There may be situations when we want to create instance objects of type Person from different types of data. For example, we may have a string that contains name and age separated by a comma, or we may have a dictionary that contains name and age.

s = 'Jack, 23'

d = {'name': 'Jane', 'age': 34}

You might read this type of data from a file or from any other place. Now you want to be able to create an instance of type Person from these types of strings and dictionaries.

Python does not support function overloading, so there can be only one type of initializer. We cannot have more than one definition for __init__ method inside a class. To initialize our objects in different ways, we can use class methods. In our Person class we will add two class methods named from_str and from_dict.

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

    @classmethod
    def from_str(cls, s):
        name, age = s.split(',')
        return cls(name, int(age))

    @classmethod
    def from_dict(cls, d):
        return cls(d['name'], d['age'])

    def display(self):
        print(f'{self.name} is {self.age} years old')

s = 'Jack, 23'
d = {'name': 'Jane', 'age': 34}
p3 = Person.from_str(s)
p3.display()
p4 = Person.from_dict(d)
p4.display()

Output-

Jack is 23 years old

Jane is 34 years old

The method from_str takes a string as argument and creates and returns a Person object, and the method from_dict creates a Person object from a dictionary.

In the from_str method, cls as usual is the first parameter and the next parameter s is for accepting a string. We split the string s to get the values of name and age. After that we create a new instance object of type Person by using these values of name and age. We know that inside the class methods, the cls parameter refers to the class object. So, cls here refers to the Person class and writing cls(name, int(age)) is equivalent to writing Person(name, int(age)) and it will create a new Person instance object. It will call __init__ to initialize the newly created object.

Similarly, our class method from_dict creates and returns a Person object from a dictionary with 'name' and 'age' as keys. We have sent the values of the dictionary as argument to the Person class initializer.

The methods from_str and from_dict are called with the class name. The instance objects that are returned by these methods are assigned to names p3 and p4.

We can see that both the factory methods internally use the __init__ method to create and return the instance objects. Instead of hardcoding the class name in these methods we have used the cls parameter to create the objects. This is good, if in future we have to rename the class or inherit a new class from this class. These factory methods would work for any class inherited from the Person class.

So, if we want to create factory methods that support inheritance, we should use class methods.

Instead of using these class methods, you might be tempted to change your __init__ so that it works with different types of input data. You might think of using default arguments or variable number of arguments and then use checks inside the method to process data differently in each case. This approach can sometimes work, but it makes the code difficult to understand and maintain. The if..elif..else construct could be confusing if there are many cases to consider. The class methods approach is simpler to understand and also increases the readability of the calling code. The __init__ method is generally a simple method that initializes the instance variables from the arguments. The alternative initializers can do additional pre-processing of data to create the instance. Rather than cluttering our __init__ method with all the code, we create separate initializers.

 

标签:__,Creating,Python,age,methods,Person,initializers,class,name
From: https://www.cnblogs.com/zhangzhihui/p/18332775

相关文章

  • 如何让 Python 请求信任自签名 SSL 证书?
    importrequestsdata={'foo':'bar'}url='https://foo.com/bar'r=requests.post(url,data=data)如果URL使用自签名证书,则会失败requests.exceptions.SSLError:[Errno1]_ssl.c:507:error:14090086:SSLroutines:SSL3_GET_SERVER_CERTIF......
  • python 偏函数
    如下代码loop=tornado.ioloop.IOLoop.current()ctx=contextvars.copy_context()func_call=functools.partial(ctx.run,func,*args,**kwargs)returnawaitloop.run_in_executor(executor,func_call)偏函数一个函数作为模板,通过提供部分参数来产生一个新的函数。......
  • Chapter 18 Python异常
    欢迎大家订阅【Python从入门到精通】专栏,一起探索Python的无限可能!文章目录前言一、什么是异常二、捕获异常三、异常的传递前言在Python中,异常是一种特定的对象,能够在程序运行过程中被抛出和处理。有效地管理异常不仅可以增强程序的稳定性,还可以提高用户体验,使程......
  • Python正则表达式匹配数字的第一次重复
    示例:For0123123123,1应匹配,因为第二个1出现在任何其他数字重复之前。For01234554321,5应该匹配,因为第二个5出现在任何其他数字的重复之前。我尝试过的一些正则表达式:......
  • 当 python 极坐标中某些列条目为空时,如何分解 List[_] 列?
    给定如下所示的Polarsdf,如何在两列上调用explode(),同时将空条目扩展到正确的长度以与其行匹配?shape:(3,2)┌───────────┬─────────────────────┐│x┆y││---┆---......
  • 使用python从网站自动下载pdf时出错
    我想从一个名为epadossier.nl的网站自动批量下载pdf我用谷歌搜索了这个并找到了一段代码并修复了一个小错误。所以现在我得到了这个`importrequestsurl="https://www.epadossier.nl/adres/plaats/straat/num"response=requests.get(url)ifresponse.status_cod......
  • 避免字符串连接的嵌套循环的 Pythonic 方法
    我想找到所有5位数字的字符串,其中前三位数字在我的第一个列表中,第二个槽第四个数字在我的第二个列表中,第三到第五个数字在我的最后一个列表中:l0=["123","567","451"]l1=["234","239","881"]l2=["348","551","399"......
  • Python 环境配置(二)安装jupyter、matplotlib、numpy库
    Python环境配置(二)安装jupyter、matplotlib、numpy库一、numpypipinstallnumpy二、matplotlibpipinstallmatplotlib三、jupyter1、anaconda自带Jupyter2、pycharm插件只有Pycharm的Professional版才支持JupyterNotebook,请注意版本3、新建文件#%......
  • 如何使用 PIPE 并行运行 python 子进程?
    我正在使用inkscape将一堆SVG图像转换为PNG。单线程:importsubprocessimporttimeimportosinkscape_path=r'C:\ProgramFiles\Inkscape\bin\inkscape.com'steps=30filenames=[]processes=[]#t_start=time.process_time()t_start=time.time()f......
  • Python sqlite3 删除数据
    要从SQLite表中删除记录,你需要使用DELETEFROM语句。要删除特定的记录,你需要同时使用WHERE子句。要更新特定的记录,你需要同时使用WHERE子句。语法以下是SQLite中DELETE查询的语法- DELETEFROMtable_name[WHEREClause]PythonCopy例子假设我们使用以下查询创建了......