[Tutor] inquire

Kalle Svensson kalle@gnupung.net
Mon, 15 Jan 2001 23:00:51 +0100


--M9NhX3UHpAaciwkO
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

Sez XIA Xiao-Qin:
> Excuse me -- I have questions again.

No problem, that's what we're here for!

> 1.Is there any way to know the type of a variable in Python.
> for example:
[snip]

Use the builtin type() and the module types.

if type(var) =3D=3D type([]):
    # do list stuff

or

import types
if type(var) =3D=3D types.ListType:
    # do list stuff

Note that often it is better to check for interfaces, rather than types:

try:
    print var[3]
except AttributeError:
    print "var is not a sequence."

In this case, I could make var an instance of a custom class, as long as I
provide the magic method __getitem__:

class Seq:
    def __getitem__(self, key):
        return 2 ** key

var =3D Seq()

try:
    print var[3]
except AttributeError:
    print "var is not a sequence."

prints 8.
Read more in the language reference, chapter 3.
http://python.org/doc/current/ref/datamodel.html


> 2. Can a method know the name of the class in which the method is defined?

import sys
class A:
    def fun(self):
        try:
	    raise
	except:
	    name =3D sys.exc_info()[2].tb_frame.f_code.co_name
	    print eval("self.%s.im_class.__name__" % name)


works most of the time, at least.  I'm a bit worried about the "get the
function name" approach, but it seems to do the right thing.

Again, more info in the language reference (3.2):
http://python.org/doc/current/ref/types.html


> And can we print the name of class B? by modify the methods fun(self) and
> newfun(self)?

That one is harder, I think.  But I'll leave it to you or someone else with
too much time to waste. <wink>

Hope this helps,
  Kalle
--=20
Email: kalle@gnupung.net     | You can tune a filesystem, but you
Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8)
PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD

--M9NhX3UHpAaciwkO
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.4 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE6Y3MTdNeA1787sd0RAoROAKCRMEaK+9P8C5v20czrc+QGu4BqqACbBQTH
Rdn7hZm1ecFtB+x908yC75U=
=YtMG
-----END PGP SIGNATURE-----

--M9NhX3UHpAaciwkO--