class FooBar:
     def __init__(self, value = 42):
         self.somevar = value

f = FooBar('This is a constructor argument')
f.somevar

This is a constructor argument

How can the parameter value know what kind of data it's going to be given? Int, float, string, etc? thanks.

Recommended Answers

All 4 Replies

???

A guess... :)

class foobar():
    def __init__(self, foo, bar):      # constructor
        self.foo = foo
        self.bar = bar

Cheers and Happy coding

Generally, type checking in Python is frowned upon. If you really feel like you need to do it, though, there are a couple ways you can do this.

You could use the isinstance() function to check the type, and raise an exception if the argument of the correct type.
For instance:

class Employee:
	def __init__(self, name=None, age=None, salary=None):
		if name and (not isinstance(name, str)):
			raise TypeError('Name must be a string.')
		if age and (not isinstance(age, int)):
			raise TypeError('Age must be an integer.')
		if salary and (not isinstance(salary, float)):
			raise TypeError('Salary must be a floating point number.')
			
		self.name = name
		self.age = age
		self.salary = salary

Thanks but I'M not trying to find another way to do it. I just want to know how that's possible.

Python assigns the type by inference.
value = 42 is an integer
value = 12.34 is a flost
value = 'top' is a string
value = (1, 2, 3) is a tuple and so on ...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.